﻿using DBHelperSQL;
using MSXML2;
using Newtonsoft.Json;
using Scripting;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.Razor.Generator;
using System.Web.UI.WebControls;
using System.Xml;


namespace U8WebAPI.Controllers
{
    public class U8Controller : ApiController
    {
        
        enum VariateType
        {
            String,
            Int32,
            Int64,
            Decimal,
            Boolean
        }

        public const string MAX_Date = "2021-4-1";


        /// <summary>
        /// 通用审核单据接口
        /// </summary>
        /// <param name="RequestData">请求的数据</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnMessage Audit([FromBody] AuditRequest RequestData)
        {
            ADODB.Connection con = null;
            string sYear = DateTime.Now.ToString("yyyy");
            string sDate = DateTime.Now.ToString("yyyy-MM-dd");

            //sYear = "2015";
            //sDate = "2015-12-30";
                

            bool IsRun = false;
            string sErrMsg = "";
            ReturnMessage returnMessage = new ReturnMessage();
            try
            {
                if (GetSQ() == false)
                {
                    throw new Exception("授权时间已到期");
                }
                if (WebApiApplication.EnableLog)
                {
                    if (string.IsNullOrEmpty(RequestData.ExtSysRequestGUID))
                    {
                        throw new Exception("请提交外部系统请求GUID");
                    }
                    if (DbHelperSQL.ExecuteScalar("SELECT 1 FROM U8InterFaceLog WHERE ExtSysRequestId='" + RequestData.ExtSysRequestGUID + "'") != null)
                    {
                        throw new Exception("外部系统请求GUID重复");
                    }
                }
                U8Login.clsLogin u8login = GetU8Login("ST", WebApiApplication.Acc, sYear, WebApiApplication.User, WebApiApplication.Password, sDate, WebApiApplication.Server, "");
                con = new ADODB.Connection();
                con.ConnectionString = u8login.UfDbName;
                con.Open();
                con.BeginTrans();
                //初始化co接口
                var VCO = new USERPCO.VoucherCO();
                IsRun=VCO.IniLogin(u8login, ref sErrMsg);
                if (IsRun==false)
                {
                    throw new Exception(sErrMsg);
                }

                //单据头校验
                if (new string[] { "01", "08", "09", "10", "11", "32","12"}.Contains(RequestData.VouchCode) == false)
                {
                    throw new Exception("单据类型代码错误");
                }
                if (RequestData.VoucherId==0)
                {
                    throw new Exception("单据主键Id错误");
                }
                string TableName = "";
                string FieldVoucherName = "";
                if (RequestData.VouchCode=="12")
                {
                    TableName = "TransVouch";
                    FieldVoucherName = "cTVCode";
                }
                else
                {
                    TableName = "rdrecord" + RequestData.VouchCode;
                    FieldVoucherName = "cCode";
                }
                if (CheckMainID(RequestData.VoucherId, TableName))
                {
                    throw new Exception("单据主键Id在系统中不存在");
                }

                string VoucherName = GetVoucherName(TableName, "Id", FieldVoucherName, RequestData.VoucherId);                   

                bool IsWorkFlow = DbHelperSQL.Exists("SELECT 1 FROM " + TableName + " WHERE Id=" + RequestData.VoucherId + " AND iswfcontrolled=1");
                if(IsWorkFlow)
                {
                    bool IsNoAudit = DbHelperSQL.Exists("SELECT 1 FROM " + TableName + " WHERE Id=" + RequestData.VoucherId + " AND iswfcontrolled=1 AND ISNULL(cCurrentAuditor,'')<>'MES'");

                    if (IsNoAudit)
                    {
                        throw new Exception("单据启动了工作流管理,当前审核节点不是[MES]节点.");
                    }
                }                

                MSXML2.IXMLDOMDocument2 HeadDom = new MSXML2.DOMDocumentClass();
                MSXML2.IXMLDOMDocument2 BodyDom = new MSXML2.DOMDocumentClass();
                MSXML2.IXMLDOMDocument2 PosDom = new MSXML2.DOMDocumentClass();


                SetMESUser(VCO, con, ref HeadDom, ref BodyDom, ref PosDom, RequestData.VouchCode, RequestData.VoucherId, RequestData.MESUserName);




                //审核单据
                AuditVoucher(VCO, con, RequestData.VouchCode, RequestData.VoucherId);
                
                //调拨单，审核其他出入库单
                if (RequestData.VouchCode=="12")
                {
                    con.CommitTrans();
                    con.BeginTrans();
                    //其他入库单
                    int QTRK_BillId = Convert.ToInt32(DbHelperSQL.ExecuteScalar("SELECT Id FROM dbo.RdRecord08 WHERE cSource='调拨' AND cBusCode='" + VoucherName + "'"));
                    SetMESUser(VCO, con, ref HeadDom, ref BodyDom, ref PosDom, "08", QTRK_BillId, RequestData.MESUserName);
                    AuditVoucher(VCO, con, "08", QTRK_BillId);
                    //其他出库单
                    int QTCK_BillId = Convert.ToInt32(DbHelperSQL.ExecuteScalar("SELECT Id FROM dbo.RdRecord09 WHERE cSource='调拨' AND cBusCode='" + VoucherName + "'"));
                    SetMESUser(VCO, con, ref HeadDom, ref BodyDom, ref PosDom, "09", QTCK_BillId, RequestData.MESUserName);
                    AuditVoucher(VCO, con, "09", QTCK_BillId);
                }

                con.CommitTrans();

                if (IsWorkFlow)
                {                    
                    SqlParameter[] Paras = new SqlParameter[] {
                        new SqlParameter("@VoucherId", RequestData.VoucherId),
                        new SqlParameter("@AccountId",WebApiApplication.Acc),
                        new SqlParameter("@AccountYear",sYear),
                        new SqlParameter("@OperatorName",WebApiApplication.User)
                    };
                    DbHelperSQL.Query(@"DECLARE @cTK_ID NVARCHAR(40),@cProcID NVARCHAR(40),@cProcInstID NVARCHAR(40),@cActivityInstID NVARCHAR(40) DECLARE @cVoucherType NVARCHAR(50) DECLARE @VoucherCode NVARCHAR(50) SELECT TOP 1 @cTK_ID=cTK_ID, @cProcID=cProcID, @cProcInstID=cProcInstID, @cActivityInstID=cActivityInstID, @cVoucherType=RTRIM(LTRIM(cVoucherType)), @VoucherCode=ExtendField3 FROM Table_Task WHERE cVoucherID=@VoucherId ORDER BY cCreateTime DESC INSERT INTO dbo.WFAudit ( id, TaskId, TaskName, VoucherId, VoucherType, VoucherCode, BizObjectId, BizEventId, ProcessId, InstanceId, ActivatyId, Opinion, Attachment, Signature, FromUserId, FromUserName, Action, AccountId, AccountYear, OperatorId, OperatorName, OperationDate, MessageId, OriginalID, OriginalName ) VALUES ( NEWID(), @cTK_ID, N'审核', @VoucherId, @cVoucherType, @VoucherCode, @cVoucherType, @cVoucherType+N'.Audit', CASE ISNULL(@cProcID,'') WHEN '' THEN '00000000-0000-0000-0000-000000000000' ELSE @cProcID END, @cProcInstID, @cActivityInstID, N'', N'', N'signature', N'', N'', 1, @AccountId, @AccountYear, @OperatorName, @OperatorName, GETDATE(), N'', N'', N'' ); UPDATE dbo.Table_Task SET cTK_State=2 WHERE cTK_ID=@cTK_ID", Paras);
                    DbHelperSQL.Query("UPDATE dbo.WF_ActiveFlow SET FlagCode=2 WHERE VoucherId='" + RequestData.VoucherId + "'");
                    DbHelperSQL.Query("UPDATE " + TableName + " SET cCurrentAuditor=NULL,iverifystate=2 WHERE iswfcontrolled=1 AND ID=" + RequestData.VoucherId);
                }


                returnMessage.VoucherName = VoucherName;
                returnMessage.Id = RequestData.VoucherId;
                returnMessage.Success = true;
                returnMessage.Message = "审核成功!";
            }
            catch (Exception ex)
            {
                if(con != null) con.RollbackTrans();
                returnMessage.VoucherName = "";
                returnMessage.Id = RequestData.VoucherId;
                returnMessage.Success = false;
                returnMessage.Message = ex.Message; ;
            }
            finally
            {
                if (con != null) con.Close();
                if (WebApiApplication.EnableLog)
                {
                    string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    string BillJson = JsonConvert.SerializeObject(RequestData);
                    CreateLog(MethodName, RequestData.ExtSysRequestGUID, BillJson, returnMessage.Success, returnMessage.VoucherName, returnMessage.Message);
                }
            }
           
            return returnMessage;
        }

        /// <summary>
        /// 其它入库单保存接口
        /// </summary>
        /// <param name="RequestData">请求的数据</param>
        /// <returns></returns>
        [HttpPost]
        public ReturnMessage SaveOtherIDO([FromBody] SaveRequest RequestData)
        {
            string ErrMsg = "";
            int Id = 0;
            List<ReturnRows> rows = new List<ReturnRows>();
            ReturnMessage returnMessage = new ReturnMessage();
            try
            {
                if (GetSQ() == false)
                {
                    throw new Exception("授权时间已到期");
                }
                if (WebApiApplication.EnableLog)
                {
                    if (string.IsNullOrEmpty(RequestData.ExtSysRequestGUID))
                    {
                        throw new Exception("请提交外部系统请求GUID");
                    }
                    if (DbHelperSQL.ExecuteScalar("SELECT 1 FROM U8InterFaceLog WHERE ExtSysRequestId='" + RequestData.ExtSysRequestGUID + "'") != null)
                    {
                        throw new Exception("外部系统请求GUID重复");
                    }
                }

                //单据头校验
                if (string.IsNullOrEmpty(RequestData.VoucherName))
                {
                    throw new Exception("单据编号必须输入");
                }
                if (RequestData.BusType!="其它入库")
                {
                    throw new Exception("业务类型错误");
                }
                if (RequestData.Bredvouch == -1)
                {
                    throw new Exception("单据红蓝标识错误");
                }
                if (string.IsNullOrEmpty(RequestData.DepCode))
                {
                    throw new Exception("部门编码不可为空");
                }
                if (CheckDepartment(RequestData.DepCode) == false)
                {
                    throw new Exception("部门编码[" + RequestData.DepCode + "]在系统中不存在");
                }
                if (CheckVoucherNo("cCode", RequestData.VoucherName, "RdRecord08") == false)
                {
                    throw new Exception("单据编号[" + RequestData.VoucherName + "]在系统中已经存在");
                }
                if (string.IsNullOrEmpty(RequestData.WhCode))
                {
                    throw new Exception("请输入仓库编码");
                }
                if (CheckWarehouse(RequestData.WhCode) == false)
                {
                    throw new Exception("仓库编码[" + RequestData.WhCode + "]在系统中不存在");
                }

                if (RequestData.Rows.Count < 1)
                {
                    throw new Exception("没有提交行明细");
                }
                int RowNo = 1;
                foreach (SaveRequestItem NowRow in RequestData.Rows)
                {
                    if (NowRow.Quantity == 0)
                    {
                        throw new Exception(string.Format("数量错误,错误行号[{0}]", RowNo));
                    }
                    if (RequestData.Bredvouch == 1 && NowRow.Quantity > 0)
                    {
                        throw new Exception(string.Format("红字单据数量必须小于0,错误行号[{0}]", RowNo));
                    }
                    if (RequestData.Bredvouch == 0 && NowRow.Quantity < 0)
                    {
                        throw new Exception(string.Format("蓝字单据数量必须大于0,错误行号[{0}]", RowNo));
                    }
                    if (string.IsNullOrEmpty(NowRow.InvCode))
                    {
                        throw new Exception(string.Format("存货编码不可为空,错误行号[{0}]", RowNo));
                    }
                    if (CheckcInvCode(NowRow.InvCode) == false)
                    {
                        throw new Exception(string.Format("存货编码[{0}]在系统中不存在,错误行号[{1}]", NowRow.InvCode, RowNo));
                    }
                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);
                    if (IsEnableBatch && string.IsNullOrEmpty(NowRow.Batch))
                    {
                        throw new Exception(string.Format("批次号不可为空,错误行号[{0}]", RowNo));
                    }
                    RowNo++;
                }
                int ID = 0;
                using (TransactionScope ts = new TransactionScope())
                {
                    int iFatherId;
                    int iChildId;
                    GetID("rd", RequestData.Rows.Count, out iFatherId, out iChildId);
                    if (CheckMainID(iFatherId, "RdRecord08") == false)
                    {
                        throw new Exception(string.Format("主表ID[" + iFatherId + "]已存在"));
                    }
                    SqlParameter[] Paras;
                    string sqlstring = "";

                    RowNo = 1;
                    //检查行表
                    foreach (SaveRequestItem NowRow in RequestData.Rows)
                    {
                        if (RowNo == 1)
                        {
                            //插入主表
                            Paras = new SqlParameter[13];
                            Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                            Paras[0].Value = iFatherId;
                            Paras[1] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                            Paras[1].Value = RequestData.VoucherName;
                            Paras[2] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                            Paras[2].Value = "其它入库";
                            Paras[3] = new SqlParameter("@cSource", SqlDbType.NVarChar, 50);
                            Paras[3].Value = "库存";
                            Paras[4] = new SqlParameter("@VT_ID", SqlDbType.Int);
                            Paras[4].Value = GetVoucherTemplateId("0301");
                            Paras[5] = new SqlParameter("@cBusCode", SqlDbType.NVarChar, 50);
                            Paras[5].Value = DBNull.Value;
                            Paras[6] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                            Paras[6].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                            Paras[7] = new SqlParameter("@cRdCode", SqlDbType.NVarChar, 5);
                            Paras[7].Value = "";//待确认
                            Paras[8] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                            Paras[8].Value = BillItemCopy(RequestData.WhCode, DBNull.Value);
                            Paras[9] = new SqlParameter("@dDate", SqlDbType.DateTime);
                            Paras[9].Value = DateTime.Now.ToString("yyyy-MM-dd");
                            Paras[10] = new SqlParameter("@bredvouch", SqlDbType.Int);
                            Paras[10].Value = BillItemCopy(RequestData.Bredvouch, DBNull.Value);
                            Paras[11] = new SqlParameter("@cMemo ", SqlDbType.NVarChar, 255);
                            Paras[11].Value = BillItemCopy(RequestData.Memo, DBNull.Value);
                            Paras[12] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                            Paras[12].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);
                            sqlstring = "INSERT INTO RdRecord08 (ID,cCode,cBusType,cSource,VT_ID,cBusCode,cDepCode,cRdCode,cWhCode,cMaker,dnmaketime,cHandler,dnverifytime,dDate,dVeriDate,bRdFlag,cVouchType,bredvouch,cMemo,cDefine11) VALUES ( @ID, @cCode, @cBusType, @cSource, @VT_ID, @cBusCode, @cDepCode, @cRdCode, @cWhCode, 'MES', GETDATE(), 'MES', GETDATE(), @dDate, CONVERT(varchar(100), GETDATE(), 102), 1, '08' ,@bredvouch,@cMemo,@cDefine11)";
                            DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                        }
                        if (CheckSubID(iChildId, "rdrecords08") == false)
                        {
                            throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                        }                        

                        bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);
                        if (IsEnableBatch && string.IsNullOrEmpty(NowRow.Batch))
                        {
                            throw new Exception(string.Format("请输入批次号,错误行号[{1}]",  RowNo));
                        }

                        string cAssUnit = GetAssUnit(NowRow.InvCode);

                        //插入子表
                        Paras = new SqlParameter[10];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                        Paras[1].Value = iChildId;
                        Paras[2] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[2].Value = RequestData.VoucherName;
                        Paras[3] = new SqlParameter("@irowno", SqlDbType.Int);
                        Paras[3].Value = RowNo;
                        Paras[4] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                        Paras[4].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                        Paras[5] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                        Paras[5].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                        Paras[6] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                        Paras[6].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                        Paras[7] = new SqlParameter("@cAssUnit", SqlDbType.NVarChar, 35);
                        Paras[7].Value = cAssUnit;
                        Paras[8] = new SqlParameter("@iTrIds", SqlDbType.BigInt);
                        Paras[8].Value = DBNull.Value;
                        Paras[9] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 255);
                        Paras[9].Value = BillItemCopy(NowRow.bMemo, DBNull.Value);

                        sqlstring = "INSERT INTO rdrecords08 (ID,AutoID,irowno,cInvCode,cBatch,iQuantity,cAssUnit,bCosting,iinvexchrate,iExpiratDateCalcu,isotype,cbsysbarcode,iTrIds,cbMemo) VALUES (@ID, @AutoID,@irowno, @cInvCode,@cBatch , @iQuantity, @cAssUnit, 1, 1, 0, 0, '||st08|'+@cCode+'|'+convert(nvarchar,@irowno),@iTrIds,@cbMemo )";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                        UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, NowRow.Quantity, true, false, false);

                        RowNo++;
                        iChildId--;
                    }
                    ID = iFatherId;
                    rows = GetVoucherAutoId("08", ID);
                    ts.Complete();
                }

                returnMessage.VoucherName = RequestData.VoucherName;
                returnMessage.Message = "其他入库单保存生单成功";
                returnMessage.Id = Id;
                returnMessage.Rows = rows;
                returnMessage.Success = true;

            }
            catch (Exception ex)
            {
                returnMessage.VoucherName = RequestData.VoucherName;
                returnMessage.Success = false;
                returnMessage.Message = ex.Message;
            }
            finally
            {
                if (WebApiApplication.EnableLog)
                {
                    string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    string BillJson = JsonConvert.SerializeObject(RequestData);
                    CreateLog(MethodName, RequestData.ExtSysRequestGUID, BillJson, returnMessage.Success, returnMessage.VoucherName, returnMessage.Message);
                }
            }

            return returnMessage;
        }

        /// <summary>
        /// 通用参照生单接口
        /// </summary>
        /// <param name="RequestData"></param>
        /// <returns></returns>
        public ReturnMessage Push([FromBody] PushRequest RequestData)
        {
            string ErrMsg = "";
            int Id = 0;
            List<ReturnRows> rows = new List<ReturnRows>();    


            ReturnMessage returnMessage = new ReturnMessage();
            try
            {
                if(GetSQ()==false)
                {
                    throw new Exception("授权时间已到期");
                }
                if (WebApiApplication.EnableLog)
                {
                    if (string.IsNullOrEmpty(RequestData.ExtSysRequestGUID))
                    {
                        throw new Exception("请提交外部系统请求GUID");
                    }
                    if (DbHelperSQL.ExecuteScalar("SELECT 1 FROM U8InterFaceLog WHERE ExtSysRequestId='" + RequestData.ExtSysRequestGUID + "'") != null)
                    {
                        throw new Exception("外部系统请求GUID重复");
                    }
                }

                //单据头校验
                if (new string[] { "01", "08", "09", "10", "11", "32", "PO", "PU", "PUReject", "PUBack", "12", "Dispatch", "SO", "MO" }.Contains(RequestData.SourceVouchCode) == false)
                {
                    throw new Exception("参照单据类型代码错误");
                }
                if (new string[] { "01", "08", "09", "10", "11", "32", "PO", "PU", "PUReject", "PUBack", "12", "Dispatch", "SO", "MO" }.Contains(RequestData.TargetVouchCode) == false)
                {
                    throw new Exception("生成单据类型代码错误");
                }
                if (string.IsNullOrEmpty(RequestData.VoucherName))
                {
                    throw new Exception("单据编号必须输入");
                }
                if (RequestData.Bredvouch == -1)
                {
                    throw new Exception("单据红蓝标识错误");
                }
                if (string.IsNullOrEmpty(RequestData.DepCode))
                {
                    throw new Exception("部门编码不可为空");
                }
                if (CheckDepartment(RequestData.DepCode) == false)
                {
                    throw new Exception("部门编码[" + RequestData.DepCode + "]在系统中不存在");
                }

                if (RequestData.Rows.Count < 1)
                {
                    throw new Exception("没有提交行明细");
                }
                int RowNo = 1;
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (NowRow.Quantity == 0)
                    {
                        throw new Exception(string.Format("数量错误,错误行号[{0}]", RowNo));
                    }
                    if (RequestData.Bredvouch == 1 && NowRow.Quantity > 0)
                    {
                        throw new Exception(string.Format("红字单据数量必须小于0,错误行号[{0}]", RowNo));
                    }
                    if (RequestData.Bredvouch == 0 && NowRow.Quantity < 0)
                    {
                        throw new Exception(string.Format("蓝字单据数量必须大于0,错误行号[{0}]", RowNo));
                    }
                    if (string.IsNullOrEmpty(NowRow.InvCode))
                    {
                        throw new Exception(string.Format("存货编码不可为空,错误行号[{0}]", RowNo));
                    }
                    if (CheckcInvCode(NowRow.InvCode) == false)
                    {
                        throw new Exception(string.Format("存货编码[{0}]在系统中不存在,错误行号[{1}]", NowRow.InvCode, RowNo));
                    }
                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);
                    if (IsEnableBatch && string.IsNullOrEmpty(NowRow.Batch))
                    {
                        throw new Exception(string.Format("U8已启用批次管理,批次号不可为空,错误行号[{0}]", RowNo));
                    }

                    //蓝字出库单需检查库存
                    if (new string[] { "09", "11", "32"}.Contains(RequestData.TargetVouchCode) == true && RequestData.Bredvouch==0)
                    {
                        if (Math.Abs(NowRow.Quantity) > GetCurrentStock(NowRow.InvCode, RequestData.WhCode, NowRow.Batch))
                        {
                            throw new Exception(string.Format("本次蓝字出库数量不能大于仓库现存量,错误行号[{0}]", RowNo));
                        }
                    }
                    //红字入库单需检查库存
                    if (new string[] { "01", "08", "10"}.Contains(RequestData.TargetVouchCode) == true && RequestData.Bredvouch == 1)
                    {
                        if (Math.Abs(NowRow.Quantity) > GetCurrentStock(NowRow.InvCode, RequestData.WhCode, NowRow.Batch))
                        {
                            throw new Exception(string.Format("本次红字入库数量不能大于仓库现存量,错误行号[{0}]", RowNo));
                        }
                    }


                    RowNo++;
                }

                //选择单据
                if (RequestData.SourceVouchCode=="PO" && RequestData.TargetVouchCode=="PU")
                {
                    //采购订单Push采购到货单
                    if(PO_Push_PU(RequestData,out ErrMsg,ref Id,ref rows) ==false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "PU" && RequestData.TargetVouchCode == "01")
                {
                    //采购到货单Push采购入库单
                    if (PU_Push_01(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "PUBack" && RequestData.TargetVouchCode == "01")
                {
                    //采购退货单Push采购入库单
                    if (PUBack_Push_01(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "Dispatch" && RequestData.TargetVouchCode == "32")
                {
                    //销售发货单Push销售出库单
                    if (Dispatch_Push_32(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "MO" && RequestData.TargetVouchCode == "10")
                {
                    //生产订单Push产成品入库单
                    if (MO_Push_10(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "PU" && RequestData.TargetVouchCode == "PUReject")
                {
                    //到货单Push拒收单
                    if (PU_Push_PUReject(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else if (RequestData.SourceVouchCode == "SOBack" && RequestData.TargetVouchCode == "32")
                {
                    //销售退货单Push销售出库单红字
                    if (Dispatch_Push_32(RequestData, out ErrMsg, ref Id, ref rows) == false)
                    {
                        throw new Exception(ErrMsg);
                    }
                }
                else
                {
                    throw new Exception("参照单据类型代码或生成单据类型代码错误");
                }

                returnMessage.VoucherName = RequestData.VoucherName;
                returnMessage.Message = "参照生单执行成功";
                returnMessage.Id = Id;
                returnMessage.Rows = rows;
                returnMessage.Success = true; 
            }
            catch (Exception ex)
            {
                returnMessage.VoucherName = RequestData.VoucherName;
                returnMessage.Success = false;
                returnMessage.Message = ex.Message;
            }
            finally
            {
                if (WebApiApplication.EnableLog)
                {
                    string MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    string BillJson = JsonConvert.SerializeObject(RequestData);
                    CreateLog(MethodName, RequestData.ExtSysRequestGUID, BillJson, returnMessage.Success, returnMessage.VoucherName, returnMessage.Message);
                }
            }
            
            return returnMessage;
        }

        #region ///单据Push业务处理

        /// <summary>
        /// 采购订单Push采购到货单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool PO_Push_PU(PushRequest RequestData,out string ErrMsg,ref int ID,ref List<ReturnRows> Rows)
        {
            ErrMsg = "";
            if (RequestData.BusType != "普通采购" && RequestData.BusType != "委外加工")
            {
                ErrMsg = "业务类型错误";
                return false;
            }
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "PU_ArrivalVouch") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                int iBillType = 0;  //单据类型 0到货单;1退货单;2拒收单
                //获取单据ID
                int iFatherId=0;
                int iChildId=0;
                GetID("PuArrival", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "PU_ArrivalVouch") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }

                string SourceIds = "";

                var query = RequestData.Rows.GroupBy(x => x.SourceId);

                foreach(var info in query)
                {
                    if(SourceIds=="")
                    {
                        SourceIds = info.Key.ToString();
                    }
                    else
                    {
                        SourceIds = SourceIds + ',' + info.Key;
                    }
                    
                }
                string sqlstring = "";
                if (RequestData.BusType== "普通采购")
                {
                    sqlstring = "SELECT 1 FROM zpurpoheader WHERE poid IN(" + SourceIds + ") GROUP BY iflowid,cbustype,cvenname,cexch_name";
                }
                else
                {
                    sqlstring = "SELECT 1 FROM om_mohead WHERE moid IN(" + SourceIds + ") GROUP BY cbustype,cvenname,cexch_name";
                }
                

                if(DbHelperSQL.Query(sqlstring).Tables[0].Rows.Count>1)
                {
                    throw new Exception("行明细的参照单据必须流程、业务类型、供应商及币种相同");
                }

                SqlParameter[] Paras;               

                int RowNo = 1;
                //检查行表
                foreach(PushRequestItem NowRow in RequestData.Rows)
                {
                    if(RowNo==1)
                    {
                        //插入主表
                        string cVenCode = "";
                        string cPTCode = "";
                        string cexch_name = "";
                        decimal iTaxRate=0;
                        decimal iExchRate=0;
                        string cPersonCode = "";
                        string cPayCode = "";
                        string cVenPUOMProtocol = "";
                        string cMemo = "";
                        string cpocode = "";
                        if (RequestData.BusType == "普通采购")
                        {
                            if (CheckTableValueExist("PO_Pomain", "POID", NowRow.SourceId) == false)
                            {
                                throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                            }
                            cpocode = DbHelperSQL.ExecuteScalar("select cPOID from PO_Pomain where POID=" + NowRow.SourceId).ToString();
                            DataSet dataSet1 = DbHelperSQL.Query("SELECT cVenCode, cPTCode, cexch_name, iTaxRate, nflat, cPersonCode, ISNULL(cPayCode,'') as cPayCode, cVenPUOMProtocol,cMemo FROM PO_Pomain WHERE cPOID = '" + cpocode + "'");
                            cVenCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cVenCode"]);
                            cPTCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPTCode"]);
                            cexch_name = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cexch_name"]);
                            iTaxRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["iTaxRate"]);
                            iExchRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["nflat"]);
                            cPersonCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPersonCode"]);
                            cPayCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPayCode"]);
                            cVenPUOMProtocol = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cVenPUOMProtocol"]);
                            cMemo = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cMemo"]);                            
                        }
                        else if (RequestData.BusType == "委外加工")
                        {
                            if (CheckTableValueExist("OM_MOMain", "MOID", NowRow.SourceId) == false)
                            {
                                throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                            }
                            cpocode = DbHelperSQL.ExecuteScalar("select cCode from OM_MOMain where moid=" + NowRow.SourceId).ToString();
                            DataSet dataSet1 = DbHelperSQL.Query("SELECT cVenCode, cPTCode, cexch_name, iTaxRate, nflat, cPersonCode, ISNULL(cPayCode,'') AS cPayCode, cVenPUOMProtocol,cMemo FROM OM_MOMain WHERE cCode = '" + cpocode + "'");
                            cVenCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cVenCode"]);
                            cPTCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPTCode"]);
                            cexch_name = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cexch_name"]);
                            iTaxRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["iTaxRate"]);
                            iExchRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["nflat"]);
                            cPersonCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPersonCode"]);
                            cPayCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPayCode"]);
                            cVenPUOMProtocol = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cVenPUOMProtocol"]);
                            cMemo = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cMemo"]);                            
                        }
                        //插入主表
                        Paras = new SqlParameter[18];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[1].Value = RequestData.VoucherName;
                        Paras[2] = new SqlParameter("@cPTCode", SqlDbType.NVarChar, 2);
                        Paras[2].Value = BillItemCopy(cPTCode, DBNull.Value);
                        Paras[3] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 8);
                        Paras[3].Value = BillItemCopy(RequestData.BusType, DBNull.Value);
                        Paras[4] = new SqlParameter("@cVenCode", SqlDbType.NVarChar, 20);
                        Paras[4].Value = cVenCode;
                        Paras[5] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[5].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[6] = new SqlParameter("@iBillType", SqlDbType.Int);
                        Paras[6].Value = iBillType;
                        Paras[7] = new SqlParameter("@cexch_name", SqlDbType.NVarChar, 8);
                        Paras[7].Value = cexch_name;
                        Paras[8] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                        Paras[8].Value = iTaxRate;
                        Paras[9] = new SqlParameter("@iExchRate", SqlDbType.Decimal);
                        Paras[9].Value = iExchRate;
                        Paras[10] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[10].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[11] = new SqlParameter("@iVTid", SqlDbType.Int);
                        Paras[11].Value = GetVoucherTemplateId("26");
                        Paras[12] = new SqlParameter("@cpocode", SqlDbType.NVarChar, 64);
                        Paras[12].Value = BillItemCopy(cpocode, DBNull.Value);
                        Paras[13] = new SqlParameter("@cPersonCode", SqlDbType.NVarChar, 20);
                        Paras[13].Value = BillItemCopy(cPersonCode, DBNull.Value);
                        Paras[14] = new SqlParameter("@cPayCode", SqlDbType.NVarChar, 3);
                        Paras[14].Value = BillItemCopy(cPayCode, DBNull.Value);
                        Paras[15] = new SqlParameter("@cVenPUOMProtocol", SqlDbType.NVarChar, 20);
                        Paras[15].Value = cVenPUOMProtocol;
                        Paras[16] = new SqlParameter("@cMemo", SqlDbType.NVarChar, 60);
                        Paras[16].Value = BillItemCopy(RequestData.Memo, cMemo);
                        Paras[17] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[17].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);

                        sqlstring = "INSERT INTO PU_ArrivalVouch (ID,cCode,cPTCode,cBusType,cVenCode,cDepCode,bNegative,iBillType,cexch_name,iTaxRate,iExchRate,dDate,cMaker,cMakeTime,cverifier,caudittime,cAuditDate,iVTid,iverifystateex,cpocode,cPersonCode,cPayCode,cVenPUOMProtocol,cMemo,csysbarcode,cDefine11) VALUES ( @ID, @cCode, @cPTCode, @cBusType, @cVenCode, @cDepCode, 0, @iBillType, @cexch_name, @iTaxRate, @iExchRate, @dDate, 'MES', GETDATE(), 'MES', GETDATE(), CONVERT(varchar(100), GETDATE(), 102), @iVTid, 2, @cpocode, @cPersonCode, @cPayCode, @cVenPUOMProtocol,@cMemo, '||pudh|'+@cCode ,@cDefine11)";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "PU_ArrivalVouchs") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }

                    string cUnitID = "";
                    decimal iPerTaxRate = 0;
                    decimal iOriCost = 0;
                    decimal iOriTaxCost = 0;
                    decimal iOriMoney = 0;
                    decimal iOriTaxPrice = 0;
                    decimal iOriSum = 0;
                    decimal iCost = 0;
                    decimal iMoney = 0;
                    decimal iTaxPrice = 0;
                    decimal iSum = 0;
                    int bTaxCost = 0;
                    decimal iArrQTY = 0;
                    decimal fPoArrQuantity = 0;
                    decimal fPoValidQuantity = 0;
                    decimal ONum = 0;
                    string cordercode = "";
                    string cbMemo = "";

                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    DataRow dataRow=null;
                    if (RequestData.BusType== "普通采购")
                    {
                        if (CheckTableValueExist("PO_Podetails", "ID", NowRow.SourceAutoId) == false)
                        {
                            throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                        if (CheckTableValueExist2("PO_Podetails", string.Format("ID={0} and cInvCode='{1}'", NowRow.SourceAutoId, NowRow.InvCode)) == false)
                        {
                            throw new Exception(string.Format("参照单据行Id[{0}]在系统中存货编码不是[2], 错误行号[{1}]", NowRow.SourceAutoId, RowNo, NowRow.InvCode));
                        }
                        dataRow = DbHelperSQL.Query("SELECT * FROM PO_Podetails WHERE ID='"+NowRow.SourceAutoId+"'").Tables[0].Rows[0];
                        cUnitID = CheckDBNULL(dataRow["cUnitID"]); //计量单位编码
                        iPerTaxRate = DataConvert(VariateType.Decimal, dataRow["iPerTaxRate"]); //表体税率
                        iOriCost = DataConvert(VariateType.Decimal, dataRow["iUnitPrice"]); //原币无税单价
                        iOriTaxCost = DataConvert(VariateType.Decimal, dataRow["iTaxPrice"]);  //原币含税单价
                        iCost = DataConvert(VariateType.Decimal, dataRow["iNatUnitPrice"]); //本币无税单价 
                        bTaxCost = DataConvert(VariateType.Int32, dataRow["bTaxCost"]); //价格标准(0无税,1含税）
                        iArrQTY = DataConvert(VariateType.Decimal, dataRow["iArrQTY"]); //到货数量 
                        fPoArrQuantity = DataConvert(VariateType.Decimal, dataRow["fPoArrQuantity"]); //到货数量
                        fPoValidQuantity = DataConvert(VariateType.Decimal, dataRow["fPoValidQuantity"]);//合格数量 
                        ONum = DataConvert(VariateType.Decimal, dataRow["iQuantity"]); //采购数量
                        cbMemo = CheckDBNULL(dataRow["cbMemo"]); //行备注
                        if (CheckTableValueExist("PO_Pomain", "POID", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }
                        cordercode = DbHelperSQL.ExecuteScalar("select cPOID from PO_Pomain where POID=" + NowRow.SourceId).ToString();
                    }
                    else if(RequestData.BusType == "委外加工")
                    {
                        if (CheckTableValueExist("OM_MODetails", "MODetailsID", NowRow.SourceAutoId) == false)
                        {
                            throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                        dataRow = DbHelperSQL.Query("SELECT * FROM OM_MODetails WHERE MODetailsID='" + NowRow.SourceAutoId + "'").Tables[0].Rows[0];
                        cUnitID = CheckDBNULL(dataRow["cUnitID"]);
                        iPerTaxRate = DataConvert(VariateType.Decimal, dataRow["iPerTaxRate"]);
                        iOriCost = DataConvert(VariateType.Decimal, dataRow["iUnitPrice"]);
                        iOriTaxCost = DataConvert(VariateType.Decimal, dataRow["iTaxPrice"]);
                        iCost = DataConvert(VariateType.Decimal, dataRow["iNatUnitPrice"]);
                        bTaxCost = DataConvert(VariateType.Int32, dataRow["bTaxCost"]);
                        iArrQTY = DataConvert(VariateType.Decimal, dataRow["iArrQTY"]);
                        ONum = DataConvert(VariateType.Decimal, dataRow["iQuantity"]);
                        cbMemo = CheckDBNULL(dataRow["cbMemo"]);
                        if (CheckTableValueExist("OM_MOMain", "MOID", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }
                        cordercode = DbHelperSQL.ExecuteScalar("select cCode from OM_MOMain where moid=" + NowRow.SourceId).ToString();
                    }
                    //修改单价小数精度为6位
                    iOriCost = Math.Round(iOriCost, 6);
                    iOriTaxCost = Math.Round(iOriTaxCost, 6);
                    iCost = Math.Round(iCost, 6);


                    //价格计算,取小数精度2位
                    iOriMoney = iOriCost * NowRow.Quantity;
                    iOriMoney = Math.Round(iOriMoney, 2);

                    iOriTaxPrice = iOriMoney * iPerTaxRate / 100;
                    iOriTaxPrice = Math.Round(iOriTaxPrice, 2);

                    iOriSum = iOriMoney + iOriTaxPrice;
                    iOriSum = Math.Round(iOriSum, 2);

                    iMoney = iCost * NowRow.Quantity;
                    iMoney = Math.Round(iMoney, 2);

                    iTaxPrice = iMoney * iPerTaxRate / 100;
                    iTaxPrice = Math.Round(iTaxPrice, 2);

                    iSum = iMoney + iPerTaxRate;
                    iSum = Math.Round(iSum, 2);

                    //判断本次到货数量
                    if (NowRow.Quantity > (ONum - iArrQTY))
                    {
                        throw new Exception(string.Format("本次到货数量不能大于采购订单未到货量, 错误行号[{0}]", RowNo));
                    }
                    iArrQTY = iArrQTY + NowRow.Quantity;  //设置最新订单到货数量
                    fPoArrQuantity = fPoArrQuantity + NowRow.Quantity;  //设置最新订单到货数量
                    fPoValidQuantity = fPoValidQuantity + NowRow.Quantity; //设置最新订单合格品数量

                    //插入子表
                    Paras = new SqlParameter[23];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@ivouchrowno", SqlDbType.Int);
                    Paras[2].Value = RowNo;
                    Paras[3] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[3].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[4] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[4].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                    Paras[5] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                    //取消到货单仓库录入Paras[5].Value = BillItemCopy(NowRows.cWhCode, DBNull.Value);
                    Paras[6] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[6].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[7] = new SqlParameter("@iPOsID", SqlDbType.Int);
                    Paras[7].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[8] = new SqlParameter("@cUnitID", SqlDbType.NVarChar, 50);
                    Paras[8].Value = cUnitID;
                    Paras[9] = new SqlParameter("@cordercode", SqlDbType.NVarChar, 50);
                    Paras[9].Value = cordercode;
                    Paras[10] = new SqlParameter("@bTaxCost", SqlDbType.Bit);
                    Paras[10].Value = bTaxCost;
                    Paras[11] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                    Paras[11].Value = iPerTaxRate; // GetInventoryiImpTaxRate(NowRows.cInvCode, iTaxRate);
                    Paras[12] = new SqlParameter("@iOriCost", SqlDbType.Decimal);
                    Paras[12].Value = iOriCost;
                    Paras[13] = new SqlParameter("@iOriTaxCost", SqlDbType.Decimal);
                    Paras[13].Value = iOriTaxCost;
                    Paras[14] = new SqlParameter("@iOriMoney", SqlDbType.Decimal);
                    Paras[14].Value = iOriMoney;
                    Paras[15] = new SqlParameter("@iOriTaxPrice", SqlDbType.Decimal);
                    Paras[15].Value = iOriTaxPrice;
                    Paras[16] = new SqlParameter("@iOriSum", SqlDbType.Decimal);
                    Paras[16].Value = iOriSum;
                    Paras[17] = new SqlParameter("@iCost", SqlDbType.Decimal);
                    Paras[17].Value = iCost;
                    Paras[18] = new SqlParameter("@iMoney", SqlDbType.Decimal);
                    Paras[18].Value = iMoney;
                    Paras[19] = new SqlParameter("@iTaxPrice", SqlDbType.Decimal);
                    Paras[19].Value = iTaxPrice;
                    Paras[20] = new SqlParameter("@iSum", SqlDbType.Decimal);
                    Paras[20].Value = iSum;
                    Paras[21] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                    Paras[21].Value = RequestData.VoucherName;
                    Paras[22] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 30);
                    Paras[22].Value = BillItemCopy(NowRow.bMemo, cbMemo);

                    sqlstring = "INSERT INTO PU_ArrivalVouchs (ID,AutoID,ivouchrowno,cInvCode,cBatch,iQuantity,fRealQuantity,fValidQuantity,iPOsID,cUnitID,cordercode,bTaxCost,iTaxRate,SoType,iinvexchrate,iExpiratDateCalcu,iOriCost,iOriTaxCost,iOriMoney,iOriTaxPrice,iOriSum,iCost,iMoney,iTaxPrice,iSum,cbsysbarcode,cbMemo) VALUES ( @ID, @AutoID, @ivouchrowno, @cInvCode,@cBatch, @iQuantity, @iQuantity, @iQuantity, @iPOsID, @cUnitID, @cordercode, @bTaxCost, @iTaxRate, 0, 1, 0, @iOriCost, @iOriTaxCost, @iOriMoney, @iOriTaxPrice, @iOriSum, @iCost, @iMoney, @iTaxPrice, @iSum, '||pudh|'+@cCode+'|'+convert(nvarchar,@ivouchrowno),@cbMemo) ";

                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    if (RequestData.BusType == "普通采购")
                    {
                        Paras = new SqlParameter[4];
                        Paras[0] = new SqlParameter("@iArrQTY", SqlDbType.Decimal);
                        Paras[0].Value = iArrQTY;
                        Paras[1] = new SqlParameter("@fPoArrQuantity", SqlDbType.Decimal);
                        Paras[1].Value = fPoArrQuantity;
                        Paras[2] = new SqlParameter("@fPoValidQuantity", SqlDbType.Decimal);
                        Paras[2].Value = fPoValidQuantity;
                        Paras[3] = new SqlParameter("@iPOsID", SqlDbType.Int);
                        Paras[3].Value = NowRow.SourceAutoId;
                        DbHelperSQL.Query("update PO_Podetails set iArrQTY=@iArrQTY, fPoArrQuantity=@fPoArrQuantity, fPoValidQuantity=@fPoValidQuantity where ID=@iPOsID", WebApiApplication.TimeOut, Paras);
                    }
                    else if (RequestData.BusType == "委外加工")
                    {
                        Paras = new SqlParameter[2];
                        Paras[0] = new SqlParameter("@iArrQTY", SqlDbType.Decimal);
                        Paras[0].Value = iArrQTY;
                        Paras[1] = new SqlParameter("@iPOsID", SqlDbType.Int);
                        Paras[1].Value = NowRow.SourceAutoId;
                        DbHelperSQL.Query("update OM_MODetails set iArrQTY=@iArrQTY where MODetailsID=@iPOsID", WebApiApplication.TimeOut, Paras);
                    }

                    RowNo++;
                    iChildId--;
                }                
                ID = iFatherId;
                Rows = GetVoucherAutoId("PU", ID);
                ts.Complete();
            }
            return true;
        }

        /// <summary>
        /// 采购到货单Push采购入库单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool PU_Push_01(PushRequest RequestData, out string ErrMsg, ref int ID, ref List<ReturnRows> Rows)
        {
            ErrMsg = "";
            if (RequestData.BusType != "普通采购" && RequestData.BusType != "委外加工")
            {
                ErrMsg = "业务类型错误";
                return false;
            }
            if(string.IsNullOrEmpty(RequestData.WhCode))
            {
                ErrMsg = "请输入仓库编码";
                return false;
            }
            if (CheckWarehouse(RequestData.WhCode) == false)
            {
                ErrMsg = "仓库编码[" + RequestData.WhCode + "]在系统中不存在";
                return false;
            }
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "RdRecord01") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                //获取单据ID
                int iFatherId;
                int iChildId;
                GetID("rd", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "RdRecord01") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }
                SqlParameter[] Paras;
                string sqlstring = "";
                string cVenCode = "";
                decimal iTaxRate = 0;
                int RowNo = 1;
                //检查行表
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (RowNo == 1)
                    {
                        //插入主表
                        
                        if (CheckTableValueExist("PU_ArrivalVouch", "ID", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }



                        DataTable DataTable1 = DbHelperSQL.Query("select cVenCode, cPTCode, cexch_name, iTaxRate, iExchRate, id, cPersonCode, cVenPUOMProtocol,cCode,dDate,cMemo,cpocode   from PU_ArrivalVouch where ID = " + NowRow.SourceId).Tables[0];
                        cVenCode = CheckDBNULL(DataTable1.Rows[0]["cVenCode"]);
                        string cPTCode = CheckDBNULL(DataTable1.Rows[0]["cPTCode"]);
                        string cexch_name = CheckDBNULL(DataTable1.Rows[0]["cexch_name"]);
                        iTaxRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iTaxRate"]);
                        decimal iExchRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iExchRate"]);
                        int ipurarriveid = DataConvert(VariateType.Int32, DataTable1.Rows[0]["id"]);
                        string cPersonCode = CheckDBNULL(DataTable1.Rows[0]["cPersonCode"]);
                        string cVenPUOMProtocol = CheckDBNULL(DataTable1.Rows[0]["cVenPUOMProtocol"]);
                        string DHcCode = CheckDBNULL(DataTable1.Rows[0]["cCode"]);
                        string DHdDate = CheckDBNULL(DataTable1.Rows[0]["dDate"]);
                        string cMemo = CheckDBNULL(DataTable1.Rows[0]["cMemo"]);
                        string cpocode = CheckDBNULL(DataTable1.Rows[0]["cpocode"]);
                        string cSource = "";
                        if (RequestData.BusType == "普通采购")
                        {
                            cSource = "采购到货单";
                        }
                        else if (RequestData.BusType == "委外加工")
                        {
                            cSource = "委外到货单";
                        }

                        string cRdCode = DbHelperSQL.ExecuteScalar("select cRdCode From PurchaseType where cPTCode ='" + cPTCode + "'").ToString();


                        //插入主表
                        Paras = new SqlParameter[23];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@bredvouch", SqlDbType.Int);
                        Paras[1].Value = BillItemCopy(RequestData.Bredvouch, DBNull.Value);
                        Paras[2] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[2].Value = RequestData.VoucherName;
                        Paras[3] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[3].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[4] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                        Paras[4].Value = BillItemCopy(RequestData.BusType, DBNull.Value);
                        Paras[5] = new SqlParameter("@cVenCode", SqlDbType.NVarChar, 20);
                        Paras[5].Value = cVenCode;
                        Paras[6] = new SqlParameter("@VT_ID", SqlDbType.Int);
                        Paras[6].Value = GetVoucherTemplateId("24");
                        Paras[7] = new SqlParameter("@cPersonCode", SqlDbType.NVarChar, 20);
                        Paras[7].Value = cPersonCode;
                        Paras[8] = new SqlParameter("@cVenPUOMProtocol", SqlDbType.NVarChar, 20);
                        Paras[8].Value = cVenPUOMProtocol;
                        Paras[9] = new SqlParameter("@cSource", SqlDbType.NVarChar, 50);
                        Paras[9].Value = cSource;
                        Paras[10] = new SqlParameter("@cRdCode", SqlDbType.NVarChar, 5);
                        Paras[10].Value = BillItemCopy(cRdCode, DBNull.Value);
                        Paras[11] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Paras[11].Value = BillItemCopy(RequestData.WhCode, DBNull.Value);
                        Paras[12] = new SqlParameter("@cARVCode", SqlDbType.NVarChar, 30);
                        Paras[12].Value =  DHcCode;
                        Paras[13] = new SqlParameter("@cexch_name", SqlDbType.NVarChar, 8);
                        Paras[13].Value = cexch_name;
                        Paras[14] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                        Paras[14].Value = iTaxRate;
                        Paras[15] = new SqlParameter("@iExchRate", SqlDbType.Decimal);
                        Paras[15].Value = iExchRate;
                        Paras[16] = new SqlParameter("@cPTCode", SqlDbType.NVarChar, 2);
                        Paras[16].Value = cPTCode;
                        Paras[17] = new SqlParameter("@ipurarriveid", SqlDbType.Int);
                        Paras[17].Value = ipurarriveid;
                        Paras[18] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[18].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[19] = new SqlParameter("@dARVDate ", SqlDbType.DateTime);
                        Paras[19].Value = BillItemCopy(DHdDate, DBNull.Value);
                        Paras[20] = new SqlParameter("@cMemo ", SqlDbType.NVarChar, 255);
                        Paras[20].Value = BillItemCopy(RequestData.Memo, cMemo);
                        Paras[21] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[21].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);
                        Paras[22] = new SqlParameter("@cOrderCode", SqlDbType.NVarChar, 30);
                        Paras[22].Value = BillItemCopy(cpocode, DBNull.Value);

                        sqlstring = "INSERT INTO RdRecord01 (ID,bredvouch,cCode,cDepCode,cBusType,cVenCode,bCredit,VT_ID,cPersonCode,cVenPUOMProtocol,cSource,cRdCode,cWhCode,cARVCode,cexch_name,iTaxRate,iExchRate,cPTCode,ipurarriveid,cMaker,dnmaketime,dDate,cHandler,dnverifytime,dVeriDate,bRdFlag,cVouchType,csysbarcode,dARVDate,cMemo,cDefine11,cOrderCode) VALUES ( @ID, @bredvouch, @cCode, @cDepCode, @cBusType, @cVenCode, 0, @VT_ID, @cPersonCode, @cVenPUOMProtocol, @cSource, @cRdCode, @cWhCode, @cARVCode, @cexch_name, @iTaxRate, @iExchRate, @cPTCode, @ipurarriveid, 'MES', GETDATE(), @dDate, 'MES', GETDATE(), CONVERT(varchar(100), GETDATE(), 102), 1, '01', '||st01|'+@cCode ,@dARVDate,@cMemo,@cDefine11,@cOrderCode) ";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "rdrecords01") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }

                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    DataRow dataRow = null;
                    if (CheckTableValueExist("PU_ArrivalVouchs", "Autoid", NowRow.SourceAutoId) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }
                    if (CheckTableValueExist2("PU_ArrivalVouchs", string.Format("Autoid={0} and cInvCode='{1}'", NowRow.SourceAutoId, NowRow.InvCode)) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中存货编码不是[2], 错误行号[{1}]", NowRow.SourceAutoId, RowNo, NowRow.InvCode));
                    }

                    DataTable DataTable2 = DbHelperSQL.Query("SELECT PU_ArrivalVouchs.cUnitID, PU_ArrivalVouchs.iTaxRate, PU_ArrivalVouchs.iOriCost, PU_ArrivalVouchs.iOriTaxCost, PU_ArrivalVouchs.iCost, PU_ArrivalVouchs.bTaxCost, PU_ArrivalVouchs.iQuantity, PU_ArrivalVouchs.iPOsID, PU_ArrivalVouchs.cordercode, PU_ArrivalVouch.cCode, ISNULL(PU_ArrivalVouchs.fValidInQuan, 0) AS fValidInQuan, CONVERT(VARCHAR(100), PU_ArrivalVouch.dDate, 23) AS dbarvdate,PU_ArrivalVouchs.cbMemo,PU_ArrivalVouchs.cDefine25 FROM PU_ArrivalVouch INNER JOIN PU_ArrivalVouchs ON PU_ArrivalVouch.ID = PU_ArrivalVouchs.ID WHERE PU_ArrivalVouchs.Autoid = " + NowRow.SourceAutoId).Tables[0];
                    string cAssUnit = CheckDBNULL(DataTable2.Rows[0]["cUnitID"]);
                    iTaxRate = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iTaxRate"]);
                    decimal iOriCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iOriCost"]);        //原币无税单价 
                    decimal iOriTaxCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iOriTaxCost"]);  //原币含税单价 
                    decimal iUnitCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iCost"]);          //本币无税单价 
                    int bTaxCost = DataConvert(VariateType.Int32, DataTable2.Rows[0]["bTaxCost"]);
                    decimal PUNum = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iQuantity"]);
                    int iPOsID = DataConvert(VariateType.Int32, DataTable2.Rows[0]["iPOsID"]);
                    string cordercode = CheckDBNULL(DataTable2.Rows[0]["cordercode"]);
                    string cbarvcode = CheckDBNULL(DataTable2.Rows[0]["cCode"]);
                    decimal fValidInQuan = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["fValidInQuan"]);
                    string dbarvdate = CheckDBNULL(DataTable2.Rows[0]["dbarvdate"]);
                    string cbMemo = CheckDBNULL(DataTable2.Rows[0]["cbMemo"]);
                    string cbDefine25 = CheckDBNULL(DataTable2.Rows[0]["cDefine25"]);

                    //将单位调整为小数6位
                    iOriCost = Math.Round(iOriCost, 6);
                    iOriTaxCost = Math.Round(iOriTaxCost, 6);
                    iUnitCost = Math.Round(iUnitCost, 6);

                    int iOMoDID = 0;
                    if (RequestData.BusType == "委外加工")
                    {
                        iOMoDID = iPOsID;
                        iPOsID = 0;
                    }

                    //计算金额，调整为小数2位
                    decimal iOriMoney = iOriCost * NowRow.Quantity;
                    iOriMoney = Math.Round(iOriMoney, 2);

                    decimal iOriTaxPrice = iOriMoney * iTaxRate / 100;
                    iOriTaxPrice = Math.Round(iOriTaxPrice, 2);

                    decimal iOriSum = iOriMoney + iOriTaxPrice;
                    iOriSum = Math.Round(iOriSum, 2);

                    decimal iPrice = iUnitCost * NowRow.Quantity;
                    iPrice = Math.Round(iPrice, 2);

                    decimal iTaxPrice = iPrice * iTaxRate / 100;
                    iTaxPrice = Math.Round(iTaxPrice, 2);

                    decimal iSum = iPrice + iTaxPrice;
                    iSum = Math.Round(iSum, 2);


                    decimal fACost = iUnitCost;
                    decimal iAPrice = iPrice;

                    if (NowRow.Quantity > (Math.Abs(PUNum) - Math.Abs(fValidInQuan)))
                    {
                        throw new Exception(string.Format("本次入库数量不能大于到货单未入库数量, 错误行号[{0}]", RowNo));
                    }
                    fValidInQuan = fValidInQuan + NowRow.Quantity;

                    decimal freceivedqty = 0;
                    decimal PONum = 0;

                    if (RequestData.BusType == "普通采购")
                    {
                        DataTable DataTable3 = DbHelperSQL.Query("select isnull(freceivedqty,0) AS freceivedqty,iQuantity AS PONum from PO_Podetails where ID = " + iPOsID).Tables[0];
                        freceivedqty = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["freceivedqty"]);
                        PONum = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["PONum"]);
                    }
                    else if (RequestData.BusType == "委外加工")
                    {
                        DataTable DataTable3 = DbHelperSQL.Query("select isnull(freceivedqty,0) AS freceivedqty,iQuantity AS PONum from OM_MODetails where MODetailsID =" + iOMoDID).Tables[0];
                        freceivedqty = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["freceivedqty"]);
                        PONum = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["PONum"]);
                    }
                    if (RequestData.Bredvouch == 1)
                    {
                        if (Math.Abs(NowRow.Quantity) > freceivedqty)
                        {
                            throw new Exception(string.Format("退货数量不能大于订单入库数量, 错误行号[{0}]", RowNo));
                        }
                    }
                    else if (RequestData.Bredvouch == 0)
                    {
                        if (NowRow.Quantity > (PONum - freceivedqty))
                        {
                            throw new Exception(string.Format("本次入库数量不能大于采购订单未入库数量, 错误行号[{0}]", RowNo));
                        }
                    }
                    freceivedqty += NowRow.Quantity;

                    //插入子表
                    Paras = new SqlParameter[31];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@chVencode", SqlDbType.NVarChar, 20);
                    Paras[2].Value = BillItemCopy(cVenCode, DBNull.Value);
                    Paras[3] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[3].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[4] = new SqlParameter("@irowno", SqlDbType.Int);
                    Paras[4].Value = BillItemCopy(RowNo, DBNull.Value);
                    Paras[5] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[5].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[6] = new SqlParameter("@PUNum", SqlDbType.Decimal);
                    Paras[6].Value = PUNum;
                    Paras[7] = new SqlParameter("@cAssUnit", SqlDbType.NVarChar, 35);
                    Paras[7].Value = cAssUnit;
                    Paras[8] = new SqlParameter("@iPOsID", SqlDbType.BigInt);
                    Paras[8].Value = BillItemCopy(iPOsID, DBNull.Value);
                    Paras[9] = new SqlParameter("@iOMoDID", SqlDbType.Int);
                    Paras[9].Value = BillItemCopy(iOMoDID, DBNull.Value);
                    Paras[10] = new SqlParameter("@iArrsId", SqlDbType.BigInt);
                    Paras[10].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[11] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);  //税率
                    Paras[11].Value = iTaxRate;
                    Paras[12] = new SqlParameter("@bTaxCost", SqlDbType.Bit);
                    Paras[12].Value = bTaxCost;
                    Paras[13] = new SqlParameter("@cOrderCode", SqlDbType.NVarChar, 30);
                    Paras[13].Value = cordercode;
                    Paras[14] = new SqlParameter("@cbarvcode", SqlDbType.NVarChar, 30);
                    Paras[14].Value = cbarvcode;
                    Paras[15] = new SqlParameter("@dbarvdate", SqlDbType.NVarChar, 30);
                    Paras[15].Value = dbarvdate;
                    Paras[16] = new SqlParameter("@iOriCost", SqlDbType.Decimal);       //原币无税单价
                    Paras[16].Value = iOriCost;
                    Paras[17] = new SqlParameter("@iOriTaxCost", SqlDbType.Decimal);    //原币含税单价 
                    Paras[17].Value = iOriTaxCost;
                    Paras[18] = new SqlParameter("@iOriMoney", SqlDbType.Decimal);      //原币无税金额 
                    Paras[18].Value = iOriMoney;
                    Paras[19] = new SqlParameter("@iOriTaxPrice", SqlDbType.Decimal);   //原币税额 
                    Paras[19].Value = iOriTaxPrice;
                    Paras[20] = new SqlParameter("@iOriSum", SqlDbType.Decimal);    //原币价税合计
                    Paras[20].Value = iOriSum;
                    Paras[21] = new SqlParameter("@iUnitCost", SqlDbType.Decimal);  //本币单价
                    Paras[21].Value = iUnitCost;
                    Paras[22] = new SqlParameter("@fACost", SqlDbType.Decimal);
                    Paras[22].Value = fACost;
                    Paras[23] = new SqlParameter("@iAPrice", SqlDbType.Decimal);
                    Paras[23].Value = iAPrice;
                    Paras[24] = new SqlParameter("@iPrice", SqlDbType.Decimal);     //本币无税金额
                    Paras[24].Value = iPrice;
                    Paras[25] = new SqlParameter("@iTaxPrice", SqlDbType.Decimal);  //本币税额 
                    Paras[25].Value = iTaxPrice;
                    Paras[26] = new SqlParameter("@iSum", SqlDbType.Decimal);       //本币价税合计
                    Paras[26].Value = iSum;
                    Paras[27] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                    Paras[27].Value = BillItemCopy(RequestData.VoucherName, DBNull.Value);
                    Paras[28] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[28].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                    Paras[29] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 255);
                    Paras[29].Value = BillItemCopy(NowRow.bMemo, cbMemo);
                    Paras[30] = new SqlParameter("@cDefine25", SqlDbType.NVarChar, 60);
                    Paras[30].Value = BillItemCopy(cbDefine25, DBNull.Value);

                    sqlstring = "INSERT INTO rdrecords01 (ID,AutoID,chVencode,cInvCode,irowno,iQuantity,iNQuantity,cAssUnit,iPOsID,iOMoDID,iArrsId,iFlag,iTaxRate,bTaxCost,cPOID,cbarvcode,dbarvdate,iOriCost,iOriTaxCost,iOriMoney,iOriTaxPrice,iOriSum,iUnitCost,fACost,iAPrice,iPrice,iTaxPrice,iSum,iSQuantity,iMoney,iExpiratDateCalcu,cbsysbarcode,bCosting,cBatch,cbMemo,cDefine25) VALUES ( @ID, @AutoID, @chVencode, @cInvCode, @irowno, @iQuantity, @PUNum, @cAssUnit, @iPOsID, @iOMoDID, @iArrsId, 0, @iTaxRate, @bTaxCost, @cOrderCode, @cbarvcode, @dbarvdate, @iOriCost, @iOriTaxCost, @iOriMoney, @iOriTaxPrice, @iOriSum, @iUnitCost, @fACost, @iAPrice, @iPrice, @iTaxPrice, @iSum, 0, 0, 0, '||st01|'+@cCode+'|'+convert(nvarchar,@irowno), 1 ,@cBatch,@cbMemo,@cDefine25)";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    DbHelperSQL.Query("update PU_ArrivalVouchs set fValidInQuan=" + fValidInQuan + ",fValidInNum=" + fValidInQuan + " where Autoid =" + NowRow.SourceAutoId);
                    if (RequestData.BusType == "普通采购")
                    {
                        DbHelperSQL.Query("update PO_Podetails set freceivedqty=" + freceivedqty + " where ID=" + iPOsID);
                    }
                    else if (RequestData.BusType == "委外加工")
                    {
                        DbHelperSQL.Query("update OM_MODetails set freceivedqty=" + freceivedqty + " where MODetailsID=" + iOMoDID);
                    }

                    UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, NowRow.Quantity, true, false, false);


                    RowNo++;
                    iChildId--;
                }

                Paras = new SqlParameter[2];
                Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                Paras[0].Value = iFatherId;
                Paras[1] = new SqlParameter("@cVouType", SqlDbType.NVarChar, 10);
                Paras[1].Value = "01";
                DbHelperSQL.RunProcedure("IA_SP_WriteUnAccountVouchForST", Paras, WebApiApplication.TimeOut);

                ID = iFatherId;
                Rows = GetVoucherAutoId("01", ID);
                ts.Complete();
            }
            return true;
        }

        /// <summary>
        /// 采购退货单Push采购入库单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool PUBack_Push_01(PushRequest RequestData, out string ErrMsg, ref int ID, ref List<ReturnRows> Rows)
        {
            ErrMsg = "";
            if (RequestData.BusType != "普通采购" && RequestData.BusType != "委外加工")
            {
                ErrMsg = "业务类型错误";
                return false;
            }
            if (string.IsNullOrEmpty(RequestData.WhCode))
            {
                ErrMsg = "请输入仓库编码";
                return false;
            }
            if (CheckWarehouse(RequestData.WhCode) == false)
            {
                ErrMsg = "仓库编码[" + RequestData.WhCode + "]在系统中不存在";
                return false;
            }
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "RdRecord01") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            if (RequestData.Bredvouch != 1)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]必须是红字单据";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                //获取单据ID
                int iFatherId;
                int iChildId;
                GetID("rd", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "RdRecord01") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }
                SqlParameter[] Paras;
                string sqlstring = "";
                string cVenCode = "";
                decimal iTaxRate = 0;
                int RowNo = 1;
                //检查行表
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (RowNo == 1)
                    {
                        //插入主表

                        if (CheckTableValueExist("PU_ArrivalVouch", "ID", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }

                        if(DbHelperSQL.Exists("select 1 from PU_ArrivalVouch where ID=" + NowRow.SourceId + " and iBillType = 1")==false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]不是采购退货单, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }

                        DataTable DataTable1 = DbHelperSQL.Query("select cVenCode, cPTCode, cexch_name, iTaxRate, iExchRate, id, cPersonCode, cVenPUOMProtocol,cCode,dDate,cMemo,cpocode   from PU_ArrivalVouch where ID = " + NowRow.SourceId).Tables[0];
                        cVenCode = CheckDBNULL(DataTable1.Rows[0]["cVenCode"]);
                        string cPTCode = CheckDBNULL(DataTable1.Rows[0]["cPTCode"]);
                        string cexch_name = CheckDBNULL(DataTable1.Rows[0]["cexch_name"]);
                        iTaxRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iTaxRate"]);
                        decimal iExchRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iExchRate"]);
                        int ipurarriveid = DataConvert(VariateType.Int32, DataTable1.Rows[0]["id"]);
                        string cPersonCode = CheckDBNULL(DataTable1.Rows[0]["cPersonCode"]);
                        string cVenPUOMProtocol = CheckDBNULL(DataTable1.Rows[0]["cVenPUOMProtocol"]);
                        string DHcCode = CheckDBNULL(DataTable1.Rows[0]["cCode"]);
                        string DHdDate = CheckDBNULL(DataTable1.Rows[0]["dDate"]);
                        string cMemo = CheckDBNULL(DataTable1.Rows[0]["cMemo"]);
                        string cpocode = CheckDBNULL(DataTable1.Rows[0]["cpocode"]);
                        string cSource = "";
                        if (RequestData.BusType == "普通采购")
                        {
                            cSource = "采购到货单";
                        }
                        else if (RequestData.BusType == "委外加工")
                        {
                            cSource = "委外到货单";
                        }

                        string cRdCode = DbHelperSQL.ExecuteScalar("select cRdCode From PurchaseType where cPTCode ='" + cPTCode + "'").ToString();


                        //插入主表
                        Paras = new SqlParameter[23];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@bredvouch", SqlDbType.Int);
                        Paras[1].Value = BillItemCopy(RequestData.Bredvouch, DBNull.Value);
                        Paras[2] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[2].Value = RequestData.VoucherName;
                        Paras[3] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[3].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[4] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                        Paras[4].Value = BillItemCopy(RequestData.BusType, DBNull.Value);
                        Paras[5] = new SqlParameter("@cVenCode", SqlDbType.NVarChar, 20);
                        Paras[5].Value = cVenCode;
                        Paras[6] = new SqlParameter("@VT_ID", SqlDbType.Int);
                        Paras[6].Value = GetVoucherTemplateId("24");
                        Paras[7] = new SqlParameter("@cPersonCode", SqlDbType.NVarChar, 20);
                        Paras[7].Value = cPersonCode;
                        Paras[8] = new SqlParameter("@cVenPUOMProtocol", SqlDbType.NVarChar, 20);
                        Paras[8].Value = cVenPUOMProtocol;
                        Paras[9] = new SqlParameter("@cSource", SqlDbType.NVarChar, 50);
                        Paras[9].Value = cSource;
                        Paras[10] = new SqlParameter("@cRdCode", SqlDbType.NVarChar, 5);
                        Paras[10].Value = BillItemCopy(cRdCode, DBNull.Value);
                        Paras[11] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Paras[11].Value = BillItemCopy(RequestData.WhCode, DBNull.Value);
                        Paras[12] = new SqlParameter("@cARVCode", SqlDbType.NVarChar, 30);
                        Paras[12].Value = DHcCode;
                        Paras[13] = new SqlParameter("@cexch_name", SqlDbType.NVarChar, 8);
                        Paras[13].Value = cexch_name;
                        Paras[14] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                        Paras[14].Value = iTaxRate;
                        Paras[15] = new SqlParameter("@iExchRate", SqlDbType.Decimal);
                        Paras[15].Value = iExchRate;
                        Paras[16] = new SqlParameter("@cPTCode", SqlDbType.NVarChar, 2);
                        Paras[16].Value = cPTCode;
                        Paras[17] = new SqlParameter("@ipurarriveid", SqlDbType.Int);
                        Paras[17].Value = ipurarriveid;
                        Paras[18] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[18].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[19] = new SqlParameter("@dARVDate ", SqlDbType.DateTime);
                        Paras[19].Value = BillItemCopy(DHdDate, DBNull.Value);
                        Paras[20] = new SqlParameter("@cMemo ", SqlDbType.NVarChar, 255);
                        Paras[20].Value = BillItemCopy(RequestData.Memo, cMemo);
                        Paras[21] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[21].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);
                        Paras[22] = new SqlParameter("@cOrderCode", SqlDbType.NVarChar, 30);
                        Paras[22].Value = BillItemCopy(cpocode, DBNull.Value);

                        sqlstring = "INSERT INTO RdRecord01 (ID,bredvouch,cCode,cDepCode,cBusType,cVenCode,bCredit,VT_ID,cPersonCode,cVenPUOMProtocol,cSource,cRdCode,cWhCode,cARVCode,cexch_name,iTaxRate,iExchRate,cPTCode,ipurarriveid,cMaker,dnmaketime,dDate,cHandler,dnverifytime,dVeriDate,bRdFlag,cVouchType,csysbarcode,dARVDate,cMemo,cDefine11,cOrderCode) VALUES ( @ID, @bredvouch, @cCode, @cDepCode, @cBusType, @cVenCode, 0, @VT_ID, @cPersonCode, @cVenPUOMProtocol, @cSource, @cRdCode, @cWhCode, @cARVCode, @cexch_name, @iTaxRate, @iExchRate, @cPTCode, @ipurarriveid, 'MES', GETDATE(), @dDate, 'MES', GETDATE(), CONVERT(varchar(100), GETDATE(), 102), 1, '01', '||st01|'+@cCode ,@dARVDate,@cMemo,@cDefine11,@cOrderCode) ";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "rdrecords01") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }

                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    DataRow dataRow = null;
                    if (CheckTableValueExist("PU_ArrivalVouchs", "Autoid", NowRow.SourceAutoId) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }
                    if (CheckTableValueExist2("PU_ArrivalVouchs", string.Format("Autoid={0} and cInvCode='{1}'", NowRow.SourceAutoId, NowRow.InvCode)) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中存货编码不是[2], 错误行号[{1}]", NowRow.SourceAutoId, RowNo, NowRow.InvCode));
                    }

                    DataTable DataTable2 = DbHelperSQL.Query("SELECT PU_ArrivalVouchs.cUnitID, PU_ArrivalVouchs.iTaxRate, PU_ArrivalVouchs.iOriCost, PU_ArrivalVouchs.iOriTaxCost, PU_ArrivalVouchs.iCost, PU_ArrivalVouchs.bTaxCost, PU_ArrivalVouchs.iQuantity, PU_ArrivalVouchs.iPOsID, PU_ArrivalVouchs.cordercode, PU_ArrivalVouch.cCode, ISNULL(PU_ArrivalVouchs.fValidInQuan, 0) AS fValidInQuan, CONVERT(VARCHAR(100), PU_ArrivalVouch.dDate, 23) AS dbarvdate,PU_ArrivalVouchs.cbMemo,PU_ArrivalVouchs.cDefine25 FROM PU_ArrivalVouch INNER JOIN PU_ArrivalVouchs ON PU_ArrivalVouch.ID = PU_ArrivalVouchs.ID WHERE PU_ArrivalVouchs.Autoid = " + NowRow.SourceAutoId).Tables[0];
                    string cAssUnit = CheckDBNULL(DataTable2.Rows[0]["cUnitID"]);
                    iTaxRate = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iTaxRate"]);
                    decimal iOriCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iOriCost"]);        //原币无税单价 
                    decimal iOriTaxCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iOriTaxCost"]);  //原币含税单价 
                    decimal iUnitCost = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iCost"]);          //本币无税单价 
                    int bTaxCost = DataConvert(VariateType.Int32, DataTable2.Rows[0]["bTaxCost"]);
                    decimal PUNum = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iQuantity"]);
                    int iPOsID = DataConvert(VariateType.Int32, DataTable2.Rows[0]["iPOsID"]);
                    string cordercode = CheckDBNULL(DataTable2.Rows[0]["cordercode"]);
                    string cbarvcode = CheckDBNULL(DataTable2.Rows[0]["cCode"]);
                    decimal fValidInQuan = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["fValidInQuan"]);
                    string dbarvdate = CheckDBNULL(DataTable2.Rows[0]["dbarvdate"]);
                    string cbMemo = CheckDBNULL(DataTable2.Rows[0]["cbMemo"]);
                    string cbDefine25 = CheckDBNULL(DataTable2.Rows[0]["cDefine25"]);

                    //将单位调整为小数6位
                    iOriCost = Math.Round(iOriCost, 6);
                    iOriTaxCost = Math.Round(iOriTaxCost, 6);
                    iUnitCost = Math.Round(iUnitCost, 6);

                    int iOMoDID = 0;
                    if (RequestData.BusType == "委外加工")
                    {
                        iOMoDID = iPOsID;
                        iPOsID = 0;
                    }

                    //计算金额，调整为小数2位
                    decimal iOriMoney = iOriCost * NowRow.Quantity;
                    iOriMoney = Math.Round(iOriMoney, 2);

                    decimal iOriTaxPrice = iOriMoney * iTaxRate / 100;
                    iOriTaxPrice = Math.Round(iOriTaxPrice, 2);

                    decimal iOriSum = iOriMoney + iOriTaxPrice;
                    iOriSum = Math.Round(iOriSum, 2);

                    decimal iPrice = iUnitCost * NowRow.Quantity;
                    iPrice = Math.Round(iPrice, 2);

                    decimal iTaxPrice = iPrice * iTaxRate / 100;
                    iTaxPrice = Math.Round(iTaxPrice, 2);

                    decimal iSum = iPrice + iTaxPrice;
                    iSum = Math.Round(iSum, 2);


                    decimal fACost = iUnitCost;
                    decimal iAPrice = iPrice;

                    if (NowRow.Quantity > (Math.Abs(PUNum) - Math.Abs(fValidInQuan)))
                    {
                        throw new Exception(string.Format("本次入库数量不能大于到货单未入库数量, 错误行号[{0}]", RowNo));
                    }
                    fValidInQuan = fValidInQuan + NowRow.Quantity;

                    decimal freceivedqty = 0;
                    decimal PONum = 0;

                    if (RequestData.BusType == "普通采购")
                    {
                        DataTable DataTable3 = DbHelperSQL.Query("select isnull(freceivedqty,0) AS freceivedqty,iQuantity AS PONum from PO_Podetails where ID = " + iPOsID).Tables[0];
                        freceivedqty = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["freceivedqty"]);
                        PONum = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["PONum"]);
                    }
                    else if (RequestData.BusType == "委外加工")
                    {
                        DataTable DataTable3 = DbHelperSQL.Query("select isnull(freceivedqty,0) AS freceivedqty,iQuantity AS PONum from OM_MODetails where MODetailsID =" + iOMoDID).Tables[0];
                        freceivedqty = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["freceivedqty"]);
                        PONum = DataConvert(VariateType.Decimal, DataTable3.Rows[0]["PONum"]);
                    }
                    if (RequestData.Bredvouch == 1)
                    {
                        if (Math.Abs(NowRow.Quantity) > freceivedqty)
                        {
                            throw new Exception(string.Format("退货数量不能大于订单入库数量, 错误行号[{0}]", RowNo));
                        }
                    }
                    else if (RequestData.Bredvouch == 0)
                    {
                        if (NowRow.Quantity > (PONum - freceivedqty))
                        {
                            throw new Exception(string.Format("本次入库数量不能大于采购订单未入库数量, 错误行号[{0}]", RowNo));
                        }
                    }
                    freceivedqty += NowRow.Quantity;

                    //插入子表
                    Paras = new SqlParameter[31];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@chVencode", SqlDbType.NVarChar, 20);
                    Paras[2].Value = BillItemCopy(cVenCode, DBNull.Value);
                    Paras[3] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[3].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[4] = new SqlParameter("@irowno", SqlDbType.Int);
                    Paras[4].Value = BillItemCopy(RowNo, DBNull.Value);
                    Paras[5] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[5].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[6] = new SqlParameter("@PUNum", SqlDbType.Decimal);
                    Paras[6].Value = PUNum;
                    Paras[7] = new SqlParameter("@cAssUnit", SqlDbType.NVarChar, 35);
                    Paras[7].Value = cAssUnit;
                    Paras[8] = new SqlParameter("@iPOsID", SqlDbType.BigInt);
                    Paras[8].Value = BillItemCopy(iPOsID, DBNull.Value);
                    Paras[9] = new SqlParameter("@iOMoDID", SqlDbType.Int);
                    Paras[9].Value = BillItemCopy(iOMoDID, DBNull.Value);
                    Paras[10] = new SqlParameter("@iArrsId", SqlDbType.BigInt);
                    Paras[10].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[11] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);  //税率
                    Paras[11].Value = iTaxRate;
                    Paras[12] = new SqlParameter("@bTaxCost", SqlDbType.Bit);
                    Paras[12].Value = bTaxCost;
                    Paras[13] = new SqlParameter("@cOrderCode", SqlDbType.NVarChar, 30);
                    Paras[13].Value = cordercode;
                    Paras[14] = new SqlParameter("@cbarvcode", SqlDbType.NVarChar, 30);
                    Paras[14].Value = cbarvcode;
                    Paras[15] = new SqlParameter("@dbarvdate", SqlDbType.NVarChar, 30);
                    Paras[15].Value = dbarvdate;
                    Paras[16] = new SqlParameter("@iOriCost", SqlDbType.Decimal);       //原币无税单价
                    Paras[16].Value = iOriCost;
                    Paras[17] = new SqlParameter("@iOriTaxCost", SqlDbType.Decimal);    //原币含税单价 
                    Paras[17].Value = iOriTaxCost;
                    Paras[18] = new SqlParameter("@iOriMoney", SqlDbType.Decimal);      //原币无税金额 
                    Paras[18].Value = iOriMoney;
                    Paras[19] = new SqlParameter("@iOriTaxPrice", SqlDbType.Decimal);   //原币税额 
                    Paras[19].Value = iOriTaxPrice;
                    Paras[20] = new SqlParameter("@iOriSum", SqlDbType.Decimal);    //原币价税合计
                    Paras[20].Value = iOriSum;
                    Paras[21] = new SqlParameter("@iUnitCost", SqlDbType.Decimal);  //本币单价
                    Paras[21].Value = iUnitCost;
                    Paras[22] = new SqlParameter("@fACost", SqlDbType.Decimal);
                    Paras[22].Value = fACost;
                    Paras[23] = new SqlParameter("@iAPrice", SqlDbType.Decimal);
                    Paras[23].Value = iAPrice;
                    Paras[24] = new SqlParameter("@iPrice", SqlDbType.Decimal);     //本币无税金额
                    Paras[24].Value = iPrice;
                    Paras[25] = new SqlParameter("@iTaxPrice", SqlDbType.Decimal);  //本币税额 
                    Paras[25].Value = iTaxPrice;
                    Paras[26] = new SqlParameter("@iSum", SqlDbType.Decimal);       //本币价税合计
                    Paras[26].Value = iSum;
                    Paras[27] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                    Paras[27].Value = BillItemCopy(RequestData.VoucherName, DBNull.Value);
                    Paras[28] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[28].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                    Paras[29] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 255);
                    Paras[29].Value = BillItemCopy(NowRow.bMemo, cbMemo);
                    Paras[30] = new SqlParameter("@cDefine25", SqlDbType.NVarChar, 60);
                    Paras[30].Value = BillItemCopy(cbDefine25, DBNull.Value);

                    sqlstring = "INSERT INTO rdrecords01 (ID,AutoID,chVencode,cInvCode,irowno,iQuantity,iNQuantity,cAssUnit,iPOsID,iOMoDID,iArrsId,iFlag,iTaxRate,bTaxCost,cPOID,cbarvcode,dbarvdate,iOriCost,iOriTaxCost,iOriMoney,iOriTaxPrice,iOriSum,iUnitCost,fACost,iAPrice,iPrice,iTaxPrice,iSum,iSQuantity,iMoney,iExpiratDateCalcu,cbsysbarcode,bCosting,cBatch,cbMemo,cDefine25) VALUES ( @ID, @AutoID, @chVencode, @cInvCode, @irowno, @iQuantity, @PUNum, @cAssUnit, @iPOsID, @iOMoDID, @iArrsId, 0, @iTaxRate, @bTaxCost, @cOrderCode, @cbarvcode, @dbarvdate, @iOriCost, @iOriTaxCost, @iOriMoney, @iOriTaxPrice, @iOriSum, @iUnitCost, @fACost, @iAPrice, @iPrice, @iTaxPrice, @iSum, 0, 0, 0, '||st01|'+@cCode+'|'+convert(nvarchar,@irowno), 1 ,@cBatch,@cbMemo,@cDefine25)";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    DbHelperSQL.Query("update PU_ArrivalVouchs set fValidInQuan=" + fValidInQuan + ",fValidInNum=" + fValidInQuan + " where Autoid =" + NowRow.SourceAutoId);
                    if (RequestData.BusType == "普通采购")
                    {
                        DbHelperSQL.Query("update PO_Podetails set freceivedqty=" + freceivedqty + " where ID=" + iPOsID);
                    }
                    else if (RequestData.BusType == "委外加工")
                    {
                        DbHelperSQL.Query("update OM_MODetails set freceivedqty=" + freceivedqty + " where MODetailsID=" + iOMoDID);
                    }

                    UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, NowRow.Quantity, true, false, false);


                    RowNo++;
                    iChildId--;
                }

                Paras = new SqlParameter[2];
                Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                Paras[0].Value = iFatherId;
                Paras[1] = new SqlParameter("@cVouType", SqlDbType.NVarChar, 10);
                Paras[1].Value = "01";
                DbHelperSQL.RunProcedure("IA_SP_WriteUnAccountVouchForST", Paras, WebApiApplication.TimeOut);

                ID = iFatherId;
                Rows = GetVoucherAutoId("01", ID);
                ts.Complete();
            }
            return true;
        }

        /// <summary>
        /// 销售发货单Push销售出库单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool Dispatch_Push_32(PushRequest RequestData, out string ErrMsg, ref int ID, ref List<ReturnRows> Rows)
        {
            ErrMsg = "";
            if (RequestData.BusType != "普通销售")
            {
                ErrMsg = "业务类型错误";
                return false;
            }
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "rdrecord32") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            if (string.IsNullOrEmpty(RequestData.WhCode))
            {
                ErrMsg = "请输入仓库编码";
                return false;
            }
            if (CheckWarehouse(RequestData.WhCode) == false)
            {
                ErrMsg = "仓库编码[" + RequestData.WhCode + "]在系统中不存在";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                //获取单据ID
                int iFatherId;
                int iChildId;
                GetID("rd", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "rdrecord32") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }
                SqlParameter[] Paras;
                string sqlstring = "";
                int RowNo = 1;
                //检查行表
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (RowNo == 1)
                    {
                        //插入主表


                        if (CheckTableValueExist("DispatchList", "DLID", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }

                        DataTable DataTable1 = DbHelperSQL.Query("select cSTCode, cCusCode, cPersonCode, caddcode, cDLCode, cinvoicecompany, cBusType, cexch_name, iExchRate,cDefine14,cMemo  From DispatchList where DLID =" + NowRow.SourceId , WebApiApplication.TimeOut).Tables[0];

                        string cSTCode = DataConvert(VariateType.String, DataTable1.Rows[0]["cSTCode"]);
                        string cCusCode = DataConvert(VariateType.String, DataTable1.Rows[0]["cCusCode"]);
                        string cPersonCode = DataConvert(VariateType.String, DataTable1.Rows[0]["cPersonCode"]);
                        string caddcode = DataConvert(VariateType.String, DataTable1.Rows[0]["caddcode"]);
                        string cDLCode = DataConvert(VariateType.String, DataTable1.Rows[0]["cDLCode"]);
                        string cinvoicecompany = DataConvert(VariateType.String, DataTable1.Rows[0]["cinvoicecompany"]);
                        string cBusType = DataConvert(VariateType.String, DataTable1.Rows[0]["cBusType"]);
                        string cexch_name = DataConvert(VariateType.String, DataTable1.Rows[0]["cexch_name"]);
                        decimal iExchRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iExchRate"]);
                        string HeadercDefine14 = DataConvert(VariateType.String, DataTable1.Rows[0]["cDefine14"]);
                        string cMemo = DataConvert(VariateType.String, DataTable1.Rows[0]["cMemo"]);

                        string cRdCode = DbHelperSQL.ExecuteScalar("select cRdCode from SaleType where cSTCode ='" + cSTCode + "'").ToString();

                        //插入主表
                        Paras = new SqlParameter[22];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[1].Value = RequestData.VoucherName;
                        Paras[2] = new SqlParameter("@bredvouch", SqlDbType.Int);
                        Paras[2].Value = BillItemCopy(RequestData.Bredvouch, DBNull.Value);
                        Paras[3] = new SqlParameter("@cDLCode", SqlDbType.BigInt);
                        Paras[3].Value = NowRow.SourceAutoId;
                        Paras[4] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                        Paras[4].Value = BillItemCopy(RequestData.BusType, cBusType);
                        Paras[5] = new SqlParameter("@cCusCode", SqlDbType.NVarChar, 20);
                        Paras[5].Value = cCusCode;
                        Paras[6] = new SqlParameter("@cPersonCode", SqlDbType.NVarChar, 20);
                        Paras[6].Value = cPersonCode;
                        Paras[7] = new SqlParameter("@cBusCode", SqlDbType.NVarChar, 30);
                        Paras[7].Value = BillItemCopy(cDLCode, DBNull.Value);
                        Paras[8] = new SqlParameter("@cRdCode", SqlDbType.NVarChar, 5);
                        Paras[8].Value = BillItemCopy(cRdCode, DBNull.Value);
                        Paras[9] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Paras[9].Value = BillItemCopy(RequestData.WhCode, DBNull.Value);
                        Paras[10] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[10].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[11] = new SqlParameter("@caddcode", SqlDbType.NVarChar, 60);
                        Paras[11].Value = caddcode;
                        Paras[12] = new SqlParameter("@cinvoicecompany", SqlDbType.NVarChar, 20);
                        Paras[12].Value = cinvoicecompany;
                        Paras[13] = new SqlParameter("@cMemo", SqlDbType.NVarChar, 12);
                        Paras[13].Value = BillItemCopy(RequestData.Memo, cMemo);
                        Paras[14] = new SqlParameter("@cexch_name", SqlDbType.NVarChar, 8);
                        Paras[14].Value = cexch_name;
                        Paras[15] = new SqlParameter("@iExchRate", SqlDbType.Float, 8);
                        Paras[15].Value = iExchRate;
                        Paras[16] = new SqlParameter("@cSTCode", SqlDbType.NVarChar, 2);
                        Paras[16].Value = cSTCode;
                        Paras[17] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[17].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[18] = new SqlParameter("@csysbarcode", SqlDbType.NVarChar, 60);
                        Paras[18].Value = @"||st32|" + RequestData.VoucherName;
                        Paras[19] = new SqlParameter("@VT_ID", SqlDbType.Int);
                        Paras[19].Value = GetVoucherTemplateId("0303");
                        Paras[20] = new SqlParameter("@cDefine14", SqlDbType.NVarChar, 120);
                        Paras[20].Value = BillItemCopy(HeadercDefine14, DBNull.Value);
                        Paras[21] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[21].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);

                        sqlstring = "INSERT INTO rdrecord32 ( ID, cCode, bredvouch, cDLCode, cBusType, cCusCode, cPersonCode, cBusCode, cSource, cRdCode, cWhCode, cDepCode, caddcode, cinvoicecompany, cMemo, cexch_name, iExchRate, cSTCode, cMaker, dnmaketime, dDate, cHandler, dnverifytime, dVeriDate, bRdFlag, cVouchType, csysbarcode, VT_ID, bOMFirst, cDefine14, cDefine11 ) VALUES (@ID, @cCode, @bredvouch, @cDLCode, @cBusType, @cCusCode, @cPersonCode, @cBusCode, '发货单', @cRdCode, @cWhCode, @cDepCode, @caddcode, @cinvoicecompany, @cMemo, @cexch_name, @iExchRate, @cSTCode, 'MES', @dDate, @dDate, 'MES', @dDate, CONVERT(VARCHAR(100), @dDate, 102), 0, '32', @csysbarcode, @VT_ID, 0, @cDefine14, @cDefine11)";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "rdrecords32") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }
                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    if (CheckTableValueExist("DispatchLists", "iDLsID", NowRow.SourceAutoId) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }
                    if (CheckTableValueExist2("DispatchLists", string.Format("iDLsID={0} and cInvCode='{1}'", NowRow.SourceAutoId, NowRow.InvCode)) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中存货编码不是[2], 错误行号[{1}]", NowRow.SourceAutoId, RowNo,NowRow.InvCode));
                    }                   

                    DataTable DataTable2 = DbHelperSQL.Query("SELECT DispatchList.cDLCode, DispatchLists.cCusInvName, DispatchLists.cUnitID, DispatchLists.iSOsID, DispatchLists.fOutQuantity, DispatchLists.iQuantity, cWhCode, DispatchLists.cDefine24, DispatchLists.cDefine25, DispatchLists.cDefine32, DispatchLists.cDefine33, DispatchLists.cMemo,idemandtype,cdemandid,idemandseq FROM DispatchList INNER JOIN DispatchLists ON DispatchList.DLID = DispatchLists.DLID WHERE DispatchLists.iDLsID =" + NowRow.SourceAutoId, WebApiApplication.TimeOut).Tables[0];
                    string cbdlcode = DataConvert(VariateType.String, DataTable2.Rows[0]["cDLCode"]);
                    string cCusInvName = DataConvert(VariateType.String, DataTable2.Rows[0]["cCusInvName"]);
                    string cAssUnit = DataConvert(VariateType.String, DataTable2.Rows[0]["cUnitID"]);
                    int iSOsID = DataConvert(VariateType.Int32, DataTable2.Rows[0]["iSOsID"]);
                    decimal FHfOutQuantity = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["fOutQuantity"]);
                    decimal FHNum = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iQuantity"]);
                    string FHcWhCode = DataConvert(VariateType.String, DataTable2.Rows[0]["cWhCode"]);
                    string BodycDefine24 = DataConvert(VariateType.String, DataTable2.Rows[0]["cDefine24"]);
                    string BodycDefine25 = DataConvert(VariateType.String, DataTable2.Rows[0]["cDefine25"]);
                    string BodycDefine32 = DataConvert(VariateType.String, DataTable2.Rows[0]["cDefine32"]);
                    string BodycDefine33 = DataConvert(VariateType.String, DataTable2.Rows[0]["cDefine33"]);
                    string cbMemo = DataConvert(VariateType.String, DataTable2.Rows[0]["cMemo"]);
                    int idemandtype = DataConvert(VariateType.Int32, DataTable2.Rows[0]["idemandtype"]);
                    string cdemandid = DataConvert(VariateType.String, DataTable2.Rows[0]["cdemandid"]);
                    int idemandseq = DataConvert(VariateType.Int32, DataTable2.Rows[0]["idemandseq"]);

                    if (FHcWhCode != RequestData.WhCode)
                    {
                        throw new Exception(string.Format("销售出库单主表中的仓库编码与参照发货单中的仓库编码不一致, 错误行号[{0}]", RowNo));
                    }

                    //蓝字发货
                    if (NowRow.Quantity > (FHNum - FHfOutQuantity) && RequestData.Bredvouch == 0)
                    {
                        throw new Exception(string.Format("当本次出库数量不能大于销售发货单的未出库数量, 错误行号[{0}]", RowNo));
                    }
                    //红字退货
                    if (NowRow.Quantity < (FHNum - FHfOutQuantity) && RequestData.Bredvouch == 1)
                    {
                        throw new Exception(string.Format("当本次退货数量不能大于销售退货单的未退货数量, 错误行号[{0}]", RowNo));
                    }
                    FHfOutQuantity += NowRow.Quantity;

                    string cSOCode = "";
                    decimal foutquantity = 0;
                    decimal SONum = 0;
                    int ipesoseq = 0;
                    string ccusinvcode = "";
                    if (DbHelperSQL.ExecuteScalar("select 1 from SO_SODetails where iSOsID= " + iSOsID) != null && RequestData.Bredvouch == 0)
                    {
                        DataTable2 = DbHelperSQL.Query("SELECT SO_SOMain.cSOCode, SO_SODetails.foutquantity, SO_SODetails.iQuantity, SO_SODetails.iRowNo, SO_SODetails.cCusInvCode FROM SO_SOMain INNER JOIN SO_SODetails ON SO_SOMain.ID = SO_SODetails.ID WHERE SO_SODetails.iSOsID = " + iSOsID, WebApiApplication.TimeOut).Tables[0];
                        cSOCode = DataConvert(VariateType.String, DataTable2.Rows[0]["cSOCode"]);
                        foutquantity = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["foutquantity"]);
                        SONum = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["iQuantity"]);
                        ipesoseq = DataConvert(VariateType.Int32, DataTable2.Rows[0]["iRowNo"]);
                        ccusinvcode = DataConvert(VariateType.String, DataTable2.Rows[0]["cCusInvCode"]);
                        if (NowRow.Quantity > (SONum - foutquantity))
                        {
                            throw new Exception(string.Format("当本次出库数量不能大于销售订单的未出库数量, 错误行号[{0}]", RowNo));
                        }
                        foutquantity += NowRow.Quantity;
                    }

                    //插入子表
                    Paras = new SqlParameter[32];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@irowno", SqlDbType.Int);
                    Paras[2].Value = RowNo;
                    Paras[3] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[3].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[4] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[4].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[5] = new SqlParameter("@ccusinvname", SqlDbType.NVarChar, 100);
                    Paras[5].Value = BillItemCopy(cCusInvName, DBNull.Value);
                    Paras[6] = new SqlParameter("@iNQuantity", SqlDbType.Decimal);
                    Paras[6].Value = BillItemCopy(FHNum, DBNull.Value);
                    Paras[7] = new SqlParameter("@cAssUnit", SqlDbType.NVarChar, 35);
                    Paras[7].Value = BillItemCopy(cAssUnit, DBNull.Value);
                    Paras[8] = new SqlParameter("@iDLsID", SqlDbType.BigInt);
                    Paras[8].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[9] = new SqlParameter("@iorderdid", SqlDbType.Int);
                    Paras[9].Value = BillItemCopy(iSOsID, DBNull.Value);
                    Paras[10] = new SqlParameter("@ipesodid", SqlDbType.NVarChar, 40);
                    Paras[10].Value = BillItemCopy(iSOsID, DBNull.Value); ;
                    Paras[11] = new SqlParameter("@cpesocode", SqlDbType.NVarChar, 40);
                    Paras[11].Value = BillItemCopy(cSOCode, DBNull.Value);
                    Paras[12] = new SqlParameter("@ipesoseq", SqlDbType.Int);
                    Paras[12].Value = BillItemCopy(ipesoseq, DBNull.Value);
                    Paras[13] = new SqlParameter("@cbdlcode", SqlDbType.NVarChar, 30);
                    Paras[13].Value = BillItemCopy(cbdlcode, DBNull.Value);
                    Paras[14] = new SqlParameter("@cbsysbarcode", SqlDbType.NVarChar, 80);
                    Paras[14].Value = @"||st32|" + RequestData.VoucherName + '|' + RowNo;
                    Paras[15] = new SqlParameter("@iordercode", SqlDbType.NVarChar, 40);
                    Paras[15].Value = BillItemCopy(cSOCode, DBNull.Value);
                    Paras[16] = new SqlParameter("@iorderseq", SqlDbType.Int);
                    Paras[16].Value = BillItemCopy(ipesoseq, DBNull.Value);
                    Paras[17] = new SqlParameter("@ccusinvcode", SqlDbType.NVarChar, 40);
                    Paras[17].Value = BillItemCopy(ccusinvcode, DBNull.Value);
                    Paras[18] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[18].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                    Paras[19] = new SqlParameter("@csocode", SqlDbType.NVarChar, 60);
                    Paras[19].Value = DBNull.Value;
                    Paras[20] = new SqlParameter("@cDefine24", SqlDbType.NVarChar, 60);
                    Paras[20].Value = BillItemCopy(BodycDefine24, DBNull.Value);
                    Paras[21] = new SqlParameter("@cDefine25", SqlDbType.NVarChar, 60);
                    Paras[21].Value = BillItemCopy(BodycDefine25, DBNull.Value);
                    Paras[22] = new SqlParameter("@cDefine32", SqlDbType.NVarChar, 120);
                    Paras[22].Value = BillItemCopy(BodycDefine32, DBNull.Value);
                    Paras[23] = new SqlParameter("@cDefine33", SqlDbType.NVarChar, 120);
                    Paras[23].Value = BillItemCopy(BodycDefine33, DBNull.Value);
                    Paras[24] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 255);
                    Paras[24].Value = BillItemCopy(NowRow.bMemo,cbMemo);
                    Paras[25] = new SqlParameter("@ipesotype", SqlDbType.Int);
                    Paras[25].Value = 1;
                    Paras[26] = new SqlParameter("@isotype", SqlDbType.Int);
                    Paras[26].Value = BillItemCopy(idemandtype, DBNull.Value);
                    Paras[27] = new SqlParameter("@isoseq", SqlDbType.Int);
                    Paras[27].Value = DBNull.Value;
                    Paras[28] = new SqlParameter("@bIAcreatebill", SqlDbType.Bit);
                    Paras[28].Value = 0;
                    Paras[29] = new SqlParameter("@bsaleoutcreatebill", SqlDbType.Bit);
                    Paras[29].Value = 0;
                    Paras[30] = new SqlParameter("@iposflag", SqlDbType.Int);
                    Paras[30].Value = DBNull.Value;
                    Paras[31] = new SqlParameter("@GCSourceId", SqlDbType.Int);
                    Paras[31].Value = 0;
                    sqlstring = "INSERT INTO rdrecords32 ( ID, AutoID, cInvCode, ccusinvname, irowno, iQuantity, iNQuantity, cAssUnit, iDLsID, iFlag, bCosting, iorderdid, ipesodid, iordertype, ipesotype, cpesocode, ipesoseq, cbdlcode, iExpiratDateCalcu, isotype, isoseq, bneedbill, cbsysbarcode, iordercode, iorderseq, ccusinvcode, cBatch, csocode, cDefine24, cDefine25, cDefine32, cDefine33, cbMemo, bIAcreatebill, bsaleoutcreatebill, iposflag, GCSourceId ) VALUES (@ID, @AutoID, @cInvCode, @ccusinvname, @irowno, @iQuantity, @iNQuantity, @cAssUnit, @iDLsID, 0, 1, @iorderdid, @ipesodid, 1, @ipesotype, @cpesocode, @ipesoseq, @cbdlcode, 0, @isotype,@isoseq, 1, @cbsysbarcode, @iordercode, @iorderseq, @ccusinvcode, @cBatch, @csocode, @cDefine24, @cDefine25, @cDefine32, @cDefine33, @cbMemo, @bIAcreatebill, @bsaleoutcreatebill, @iposflag, @GCSourceId )";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    DbHelperSQL.Query("update DispatchLists set fOutQuantity = fOutQuantity +" + NowRow.Quantity + " where iDLsID = " + NowRow.SourceAutoId, WebApiApplication.TimeOut);

                    if (DbHelperSQL.ExecuteScalar("select 1 from SO_SODetails where iSOsID= " + iSOsID) != null)
                    {
                        DbHelperSQL.Query("update SO_SODetails set fOutQuantity = fOutQuantity + " + NowRow.Quantity + " where iSOsID = " + iSOsID, WebApiApplication.TimeOut);

                    }
                    if (RequestData.Bredvouch == 0)
                    {
                        //蓝字
                        UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, NowRow.Quantity, false, false, true);
                    }
                    else if (RequestData.Bredvouch == 1)
                    {
                        //红字
                        UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, Math.Abs(NowRow.Quantity), true, false, true);
                    }

                    //更新发货单的出库单号
                    sqlstring = " update DispatchList set cSaleOut='ST' where cDLCode='" + cbdlcode + "'";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut);

                    RowNo++;
                    iChildId--;
                }

                Paras = new SqlParameter[4];
                Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                Paras[0].Value = iFatherId;
                Paras[1] = new SqlParameter("@cVouType", SqlDbType.NVarChar, 10);
                Paras[1].Value = "32";
                Paras[2] = new SqlParameter("@cSource", SqlDbType.NVarChar, 50);
                Paras[2].Value = "发货单";
                Paras[3] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                Paras[3].Value = BillItemCopy(RequestData.BusType, DBNull.Value);

                //写入其他出库单预算项目信息,需要确认是否有启用扩展项
                //sqlstring = " INSERT INTO dbo.rdrecord32_extradefine (ID,chdefine1) VALUES (@ID,NULL)";
                //DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);                

                DbHelperSQL.RunProcedure("IA_SP_WriteUnAccountVouchForST32", Paras, WebApiApplication.TimeOut);


                ID = iFatherId;
                Rows = GetVoucherAutoId("32", ID);
                ts.Complete();
            }
            return true;
        }

        /// <summary>
        /// 生产订单Push产成品入库单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool MO_Push_10(PushRequest RequestData, out string ErrMsg, ref int ID, ref List<ReturnRows> Rows)
        {
            ErrMsg = "";
            if (RequestData.BusType != "成品入库")
            {
                ErrMsg = "业务类型错误";
                return false;
            }
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "rdrecord10") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            if (string.IsNullOrEmpty(RequestData.WhCode))
            {
                ErrMsg = "请输入仓库编码";
                return false;
            }
            if (CheckWarehouse(RequestData.WhCode) == false)
            {
                ErrMsg = "仓库编码[" + RequestData.WhCode + "]在系统中不存在";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                //获取单据ID
                int iFatherId;
                int iChildId;
                GetID("rd", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "rdrecord10") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }
                SqlParameter[] Paras;
                string sqlstring = "";
                int RowNo = 1;
                //检查行表
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (RowNo == 1)
                    {
                        //插入主表

                        if (CheckTableValueExist("mom_order", "MoId", NowRow.SourceId) == false)
                        {
                            throw new Exception(string.Format("参照单据Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceId, RowNo));
                        }
                        string MoCode = Convert.ToString(DbHelperSQL.ExecuteScalar("select MoCode from mom_order where MoId=" + NowRow.SourceId ));

                        //插入主表
                        Paras = new SqlParameter[15];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[1].Value = RequestData.VoucherName;
                        Paras[2] = new SqlParameter("@bredvouch", SqlDbType.Int);
                        Paras[2].Value = BillItemCopy(RequestData.Bredvouch, DBNull.Value);
                        Paras[3] = new SqlParameter("@VT_ID", SqlDbType.Int);
                        Paras[3].Value = GetVoucherTemplateId("0441");
                        Paras[4] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[4].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[5] = new SqlParameter("@cRdCode", SqlDbType.NVarChar, 5);
                        Paras[5].Value = "RWF";
                        Paras[6] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Paras[6].Value = BillItemCopy(RequestData.WhCode, DBNull.Value);
                        Paras[7] = new SqlParameter("@cMPoCode", SqlDbType.NVarChar, 30);
                        Paras[7].Value = BillItemCopy(MoCode, DBNull.Value);
                        Paras[8] = new SqlParameter("@iproorderid", SqlDbType.BigInt);
                        Paras[8].Value = NowRow.SourceId;
                        Paras[9] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[9].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[10] = new SqlParameter("@cMemo", SqlDbType.NVarChar, 255);
                        Paras[10].Value = BillItemCopy(RequestData.Memo, DBNull.Value);
                        Paras[11] = new SqlParameter("@csysbarcode", SqlDbType.NVarChar, 60);
                        Paras[11].Value = @"||st10|" + RequestData.VoucherName;
                        Paras[12] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[12].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);
                        Paras[13] = new SqlParameter("@cProBatch", SqlDbType.NVarChar, 50);
                        Paras[13].Value = BillItemCopy(NowRow.Batch, DBNull.Value);//生产批号
                        Paras[14] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 12);
                        Paras[14].Value = BillItemCopy(RequestData.BusType, DBNull.Value);

                        sqlstring = "INSERT INTO rdrecord10 ( ID, cCode, bredvouch, cBusType, cSource, VT_ID, cDepCode, cRdCode, cWhCode, cMPoCode, iproorderid, cMaker, dnmaketime, dDate, cHandler, dnverifytime, dVeriDate, cMemo, bRdFlag, cVouchType, csysbarcode,cDefine11, cProBatch ) VALUES (@ID, @cCode, @bredvouch, @cBusType, '生产订单', @VT_ID, @cDepCode, @cRdCode, @cWhCode, @cMPoCode, @iproorderid, 'MES', GETDATE(), @dDate,'MES',GETDATE(),CONVERT(varchar(100), GETDATE(), 102), @cMemo, 1, '10', @csysbarcode, @cDefine11, @cProBatch)";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "rdrecords10") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }
                    

                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    if (CheckTableValueExist("mom_orderdetail", "MoDId", NowRow.SourceAutoId) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }
                    if (CheckTableValueExist2("mom_orderdetail", string.Format("MoDId={0} and InvCode='{1}'", NowRow.SourceAutoId, NowRow.InvCode)) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中存货编码不是[2], 错误行号[{1}]", NowRow.SourceAutoId, RowNo, NowRow.InvCode));
                    }

                    if (DbHelperSQL.ExecuteScalar("select 1 from mom_orderdetail where MoDId =" + NowRow.SourceAutoId + " and Status=4") != null)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]已经关闭, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }
                    string cmocode = DbHelperSQL.ExecuteScalar("select mocode from mom_order inner join mom_orderdetail on mom_order.moid = mom_orderdetail.moid where MoDId = " + NowRow.SourceAutoId).ToString();
                    
                    DataTable DataTable2 = DbHelperSQL.Query("SELECT AuxUnitCode, SortSeq, Qty, QualifiedInQty FROM mom_orderdetail WHERE MoDId = " + NowRow.SourceAutoId).Tables[0];

                    string cAssUnit = DataConvert(VariateType.String, DataTable2.Rows[0]["AuxUnitCode"]);
                    int imoseq = DataConvert(VariateType.Int32, DataTable2.Rows[0]["SortSeq"]);
                    decimal Qty = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["Qty"]);
                    decimal QualifiedInQty = DataConvert(VariateType.Decimal, DataTable2.Rows[0]["QualifiedInQty"]);

                    if (RequestData.Bredvouch == 0)
                    {
                        if (NowRow.Quantity <= 0)
                        {
                            throw new Exception(string.Format("产成品入库单数量必须大于0, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                        if (NowRow.Quantity > (Qty - QualifiedInQty))
                        {
                            throw new Exception(string.Format("本次入库数量不能大于生产订单未入库数量, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                    }
                    else
                    {
                        if (NowRow.Quantity >= 0)
                        {
                            throw new Exception(string.Format("红字产成品入库单数量必须小于0, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                        if (Math.Abs(NowRow.Quantity) > GetCurrentStock(NowRow.InvCode, RequestData.WhCode, NowRow.Batch))
                        {
                            throw new Exception(string.Format("本次红字入库数量不能大于仓库现存量, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                        if (Math.Abs(NowRow.Quantity) > QualifiedInQty)
                        {
                            throw new Exception(string.Format("本次红字入库数量不能大于生产订单已入库数量, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                        }
                    }

                    QualifiedInQty += NowRow.Quantity;
                    //按领料比例控制入库
                    if (Convert.ToInt32(GetSystemConfig("ST", "iMOProInCtrlBySet")) == 2)
                    {
                        if (CheckMOPickingTheProportion(RowNo, NowRow.SourceAutoId, NowRow.Quantity, out string Msg) == false)
                        {
                            throw new Exception(Msg);
                        }
                    }

                    //插入子表
                    Paras = new SqlParameter[13];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[2].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[3] = new SqlParameter("@irowno", SqlDbType.Int);
                    Paras[3].Value = RowNo;
                    Paras[4] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[4].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[5] = new SqlParameter("@cAssUnit", SqlDbType.NVarChar, 35);
                    Paras[5].Value = cAssUnit;
                    Paras[6] = new SqlParameter("@cmocode", SqlDbType.NVarChar, 30);
                    Paras[6].Value = cmocode;
                    Paras[7] = new SqlParameter("@iNQuantity", SqlDbType.Decimal);
                    Paras[7].Value = Qty;
                    Paras[8] = new SqlParameter("@iMPoIds", SqlDbType.BigInt);
                    Paras[8].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[9] = new SqlParameter("@imoseq", SqlDbType.Int);
                    Paras[9].Value = imoseq;
                    Paras[10] = new SqlParameter("@cbsysbarcode", SqlDbType.NVarChar, 80);
                    Paras[10].Value = @"||st10|" + RequestData.VoucherName + @"|" + RowNo;
                    Paras[11] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[11].Value = CheckBatch(IsEnableBatch, NowRow.Batch);
                    Paras[12] = new SqlParameter("@cbMemo", SqlDbType.NVarChar, 255);
                    Paras[12].Value = BillItemCopy(NowRow.bMemo, DBNull.Value);

                    sqlstring = "INSERT INTO rdrecords10 (ID,AutoID,cInvCode,irowno,iQuantity,cAssUnit,cmocode,iNQuantity,iMPoIds,iFlag,bCosting,imoseq,iExpiratDateCalcu,cbsysbarcode,cBatch,cbMemo) VALUES ( @ID, @AutoID, @cInvCode, @irowno, @iQuantity, @cAssUnit, @cmocode, @iNQuantity, @iMPoIds, 0, 1, @imoseq, 0, @cbsysbarcode, @cBatch, @cbMemo )";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    DbHelperSQL.Query("update mom_orderdetail set QualifiedInQty=" + QualifiedInQty + " where MoDId =" + NowRow.SourceAutoId);

                    //关闭生产订单
                    int MoCloseType = Convert.ToInt32(DbHelperSQL.ExecuteScalar("SELECT MoCloseType FROM mom_parameter"));
                    if (MoCloseType == 2 && Qty == QualifiedInQty)
                    {
                        DbHelperSQL.Query("update mom_orderdetail set Status=4 where MoDId =" + NowRow.SourceAutoId);
                    }

                    UpdateCurrentStock(IsEnableBatch, RequestData.WhCode, NowRow.InvCode, NowRow.Batch, NowRow.Quantity, true, false, false);

                    RowNo++;
                    iChildId--;
                }

                Paras = new SqlParameter[2];
                Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                Paras[0].Value = iFatherId;
                Paras[1] = new SqlParameter("@cVouType", SqlDbType.NVarChar, 10);
                Paras[1].Value = "10";
                DbHelperSQL.RunProcedure("IA_SP_WriteUnAccountVouchForST", Paras, WebApiApplication.TimeOut);

                ID = iFatherId;
                Rows = GetVoucherAutoId("10", ID);
                ts.Complete();
            }
            return true;
        }

        /// <summary>
        /// 到货单Push拒收单
        /// </summary>
        /// <param name="RequestData">请求数据</param>
        /// <param name="ErrMsg">错误消息</param>
        /// <param name="ID">返回的单据ID</param>
        /// <param name="returnRows">返回的行主键Id </param>
        private bool PU_Push_PUReject(PushRequest RequestData, out string ErrMsg, ref int ID, ref List<ReturnRows> Rows)
        {
            ErrMsg = "";

            if(RequestData.Bredvouch==0)
            {
                ErrMsg = "拒收单必须是红字单据";
                return false;
            }
            
            if (CheckVoucherNo("cCode", RequestData.VoucherName, "PU_ArrivalVouch") == false)
            {
                ErrMsg = "单据编号[" + RequestData.VoucherName + "]在系统中已经存在";
                return false;
            }
            using (TransactionScope ts = new TransactionScope())
            {
                int iBillType = 2;  //单据类型 0到货单;1退货单;2拒收单
                //获取单据ID
                int iFatherId = 0;
                int iChildId = 0;
                GetID("PuArrival", RequestData.Rows.Count, out iFatherId, out iChildId);
                if (CheckMainID(iFatherId, "PU_ArrivalVouch") == false)
                {
                    ErrMsg = "主表ID[" + iFatherId + "]已存在";
                    return false;
                }

                string SourceIds = "";

                var query = RequestData.Rows.GroupBy(x => x.SourceId);

                foreach (var info in query)
                {
                    if (SourceIds == "")
                    {
                        SourceIds = info.Key.ToString();
                    }
                    else
                    {
                        SourceIds = SourceIds + ',' + info.Key;
                    }

                }
                string sqlstring = "SELECT 1 FROM pu_ArrHead WHERE id IN(" + SourceIds + ") GROUP BY iflowid,cbustype,cvenname,cexch_name";         


                if (DbHelperSQL.Query(sqlstring).Tables[0].Rows.Count > 1)
                {
                    throw new Exception("行明细的参照单据必须流程、业务类型、供应商及币种相同");
                }

                SqlParameter[] Paras;
                decimal iTaxRate = 0;
                string cBusType = "普通采购";
                int RowNo = 1;
                //检查行表
                foreach (PushRequestItem NowRow in RequestData.Rows)
                {
                    if (RowNo == 1)
                    {
                        DataSet dataSet1 = DbHelperSQL.Query("SELECT cVenCode, cPTCode, cexch_name, iTaxRate, iExchRate,cMemo,cPersonCode,cBusType  FROM PU_ArrivalVouch WHERE Id = " + NowRow.SourceId);
                        string cVenCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cVenCode"]);
                        string cPTCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPTCode"]);
                        string cexch_name = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cexch_name"]);
                        iTaxRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["iTaxRate"]);
                        decimal iExchRate = DataConvert(VariateType.Decimal, dataSet1.Tables[0].Rows[0]["iExchRate"]);
                        string cMemo = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cMemo"]);
                        string cPersonCode = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cPersonCode"]);
                        cBusType = CheckDBNULL(dataSet1.Tables[0].Rows[0]["cBusType"]);

                        //插入主表
                        Paras = new SqlParameter[15];
                        Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                        Paras[0].Value = iFatherId;
                        Paras[1] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
                        Paras[1].Value = RequestData.VoucherName;
                        Paras[2] = new SqlParameter("@cPTCode", SqlDbType.NVarChar, 2);
                        Paras[2].Value = cPTCode;
                        Paras[3] = new SqlParameter("@cBusType", SqlDbType.NVarChar, 8);
                        Paras[3].Value = BillItemCopy(cBusType, DBNull.Value);
                        Paras[4] = new SqlParameter("@cVenCode", SqlDbType.NVarChar, 20);
                        Paras[4].Value = cVenCode;
                        Paras[5] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
                        Paras[5].Value = BillItemCopy(RequestData.DepCode, DBNull.Value);
                        Paras[6] = new SqlParameter("@iBillType", SqlDbType.Int);
                        Paras[6].Value = iBillType;
                        Paras[7] = new SqlParameter("@cexch_name", SqlDbType.NVarChar, 8);
                        Paras[7].Value = cexch_name;
                        Paras[8] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                        Paras[8].Value = iTaxRate;
                        Paras[9] = new SqlParameter("@iExchRate", SqlDbType.Decimal);
                        Paras[9].Value = iExchRate;
                        Paras[10] = new SqlParameter("@dDate", SqlDbType.DateTime);
                        Paras[10].Value = DateTime.Now.ToString("yyyy-MM-dd");
                        Paras[11] = new SqlParameter("@iVTid", SqlDbType.Int);
                        Paras[11].Value = GetVoucherTemplateId("26");
                        Paras[12] = new SqlParameter("@cMemo", SqlDbType.NVarChar, 255);
                        Paras[12].Value = BillItemCopy(RequestData.Memo, cMemo);
                        Paras[13] = new SqlParameter("@cPersonCode", SqlDbType.NVarChar, 20);
                        Paras[13].Value = BillItemCopy(cPersonCode, DBNull.Value);
                        Paras[14] = new SqlParameter("@cDefine11", SqlDbType.NVarChar, 60);
                        Paras[14].Value = BillItemCopy(RequestData.MESUserName, DBNull.Value);

                        sqlstring = "INSERT INTO PU_ArrivalVouch (ID,cCode,cPTCode,cBusType,cVenCode,cDepCode,bNegative,iBillType,cexch_name,iTaxRate,iExchRate,dDate,cMaker,cMakeTime,cverifier,caudittime,cAuditDate,iVTid,iverifystateex,cMemo,cPersonCode,cDefine11) VALUES ( @ID, @cCode, @cPTCode, @cBusType, @cVenCode, @cDepCode, 1, @iBillType, @cexch_name, @iTaxRate, @iExchRate, @dDate, 'MES', GETDATE(), 'MES', GETDATE(), CONVERT(varchar(100), GETDATE(), 102), @iVTid, 2 ,@cMemo,@cPersonCode,@cDefine11)";
                        DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);
                    }
                    if (CheckSubID(iChildId, "PU_ArrivalVouchs") == false)
                    {
                        throw new Exception(string.Format("子表ID[{0}]在系统中已经存在,错误行号[{1}]", iChildId, RowNo));
                    }
                    if (NowRow.Quantity >= 0)
                    {
                        throw new Exception(string.Format("拒收数量必须为负数,错误行号[{0}]", RowNo));
                    }

                    if (CheckTableValueExist("PU_ArrivalVouchs", "Autoid", NowRow.SourceAutoId) == false)
                    {
                        throw new Exception(string.Format("参照单据行Id[{0}]在系统中不存在, 错误行号[{1}]", NowRow.SourceAutoId, RowNo));
                    }

                    decimal iOriMoney = 0;
                    decimal iOriTaxPrice = 0;
                    decimal iOriSum = 0;
                    decimal iMoney = 0;
                    decimal iTaxPrice = 0;
                    decimal iSum = 0;
                    decimal iArrQTY = 0;

                    DataTable DataTable1 = DbHelperSQL.Query("select PU_ArrivalVouchs.cUnitID, PU_ArrivalVouchs.iTaxRate, PU_ArrivalVouchs.iOriCost, PU_ArrivalVouchs.iOriTaxCost , PU_ArrivalVouchs.iCost , PU_ArrivalVouchs.bTaxCost, PU_ArrivalVouchs.iQuantity, PU_ArrivalVouchs.iPOsID, PU_ArrivalVouchs.cordercode, PU_ArrivalVouch.cCode, isnull(PU_ArrivalVouchs.fRealQuantity,0) AS fRealQuantity, isnull(PU_ArrivalVouchs.fValidQuantity,0) AS fValidQuantity, isnull(PU_ArrivalVouchs.fRefuseQuantity,0) AS fRefuseQuantity, isnull(PU_ArrivalVouchs.fSumRefuseQuantity,0) AS fSumRefuseQuantity FROM PU_ArrivalVouch INNER JOIN PU_ArrivalVouchs ON PU_ArrivalVouch.ID = PU_ArrivalVouchs.ID WHERE PU_ArrivalVouchs.Autoid =" + NowRow.SourceAutoId).Tables[0];
                    string cUnitID = CheckDBNULL(DataTable1.Rows[0]["cUnitID"]);
                    iTaxRate = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iTaxRate"]);
                    decimal iOriCost = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iOriCost"]);
                    decimal iOriTaxCost = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iOriTaxCost"]);
                    decimal iCost = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["iCost"]);
                    int bTaxCost = DataConvert(VariateType.Int32, DataTable1.Rows[0]["bTaxCost"]);
                    int ONum = DataConvert(VariateType.Int32, DataTable1.Rows[0]["iQuantity"]);
                    int iPOsID = DataConvert(VariateType.Int32, DataTable1.Rows[0]["iPOsID"]);
                    string cordercode = CheckDBNULL(DataTable1.Rows[0]["cordercode"]);
                    string carrivalcode = CheckDBNULL(DataTable1.Rows[0]["cCode"]);
                    decimal fRealQuantity = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["fRealQuantity"]);
                    decimal fValidQuantity = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["fValidQuantity"]);
                    decimal fRefuseQuantity = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["fRefuseQuantity"]);
                    decimal fSumRefuseQuantity = DataConvert(VariateType.Decimal, DataTable1.Rows[0]["fSumRefuseQuantity"]);

                    iOriCost = Math.Round(iOriCost, 6);
                    iOriTaxCost = Math.Round(iOriTaxCost, 6);
                    iCost = Math.Round(iCost, 6);

                    //价格计算
                    iOriMoney = iOriCost * NowRow.Quantity;
                    iOriTaxPrice = iOriMoney * iTaxRate / 100;
                    iOriSum = iOriMoney + iOriTaxPrice;
                    iMoney = iCost * NowRow.Quantity;
                    iTaxPrice = iMoney * iTaxRate / 100;
                    iSum = iMoney + iTaxRate;

                    //设置价格精度
                    iOriMoney = Math.Round(iOriMoney, 2);
                    iOriTaxPrice = Math.Round(iOriTaxPrice, 2);
                    iOriSum = Math.Round(iOriSum, 2);
                    iMoney = Math.Round(iMoney, 2);
                    iTaxPrice = Math.Round(iTaxPrice, 2);
                    iSum = Math.Round(iSum, 2);

                    //判断本次拒收数量
                    if (Math.Abs(NowRow.Quantity) > fRealQuantity)
                    {
                        throw new Exception(string.Format("本次拒收数量不能大于到货单的实收数量, 错误行号[{0}]", RowNo));
                    }
                    if (cBusType == "普通采购")
                    {
                        iArrQTY = Convert.ToInt32(DbHelperSQL.ExecuteScalar("select iArrQTY from PO_Podetails where ID=" + iPOsID));
                    }
                    else if (cBusType == "委外加工")
                    {
                        iArrQTY = Convert.ToInt32(DbHelperSQL.ExecuteScalar("select iArrQTY from OM_MODetails where MODetailsID=" + iPOsID));
                    }
                    iArrQTY += NowRow.Quantity;  //设置最新订单到货数量

                    bool IsEnableBatch = CheckSystemIsBatch(NowRow.InvCode);

                    //插入子表
                    Paras = new SqlParameter[22];
                    Paras[0] = new SqlParameter("@ID", SqlDbType.Int);
                    Paras[0].Value = iFatherId;
                    Paras[1] = new SqlParameter("@AutoID", SqlDbType.Int);
                    Paras[1].Value = iChildId;
                    Paras[2] = new SqlParameter("@ivouchrowno", SqlDbType.Int);
                    Paras[2].Value = RowNo;
                    Paras[3] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                    Paras[3].Value = BillItemCopy(NowRow.InvCode, DBNull.Value);
                    Paras[4] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                    Paras[4].Value = BillItemCopy(NowRow.Quantity, DBNull.Value);
                    Paras[5] = new SqlParameter("@iPOsID", SqlDbType.Int);
                    Paras[5].Value = iPOsID;
                    Paras[6] = new SqlParameter("@cUnitID", SqlDbType.NVarChar, 50);
                    Paras[6].Value = cUnitID;
                    Paras[7] = new SqlParameter("@iCorId", SqlDbType.Int);
                    Paras[7].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);
                    Paras[8] = new SqlParameter("@cordercode", SqlDbType.NVarChar, 50);
                    Paras[8].Value = cordercode;
                    Paras[9] = new SqlParameter("@carrivalcode", SqlDbType.NVarChar, 80);
                    Paras[9].Value = carrivalcode;
                    Paras[10] = new SqlParameter("@bTaxCost", SqlDbType.Bit);
                    Paras[10].Value = bTaxCost;
                    Paras[11] = new SqlParameter("@iTaxRate", SqlDbType.Decimal);
                    Paras[11].Value = iTaxRate;
                    Paras[12] = new SqlParameter("@iOriCost", SqlDbType.Decimal);
                    Paras[12].Value = iOriCost;
                    Paras[13] = new SqlParameter("@iOriTaxCost", SqlDbType.Decimal);
                    Paras[13].Value = iOriTaxCost;
                    Paras[14] = new SqlParameter("@iOriMoney", SqlDbType.Decimal);
                    Paras[14].Value = iOriMoney;
                    Paras[15] = new SqlParameter("@iOriTaxPrice", SqlDbType.Decimal);
                    Paras[15].Value = iOriTaxPrice;
                    Paras[16] = new SqlParameter("@iOriSum", SqlDbType.Decimal);
                    Paras[16].Value = iOriSum;
                    Paras[17] = new SqlParameter("@iCost", SqlDbType.Decimal);
                    Paras[17].Value = iCost;
                    Paras[18] = new SqlParameter("@iMoney", SqlDbType.Decimal);
                    Paras[18].Value = iMoney;
                    Paras[19] = new SqlParameter("@iTaxPrice", SqlDbType.Decimal);
                    Paras[19].Value = iTaxPrice;
                    Paras[20] = new SqlParameter("@iSum", SqlDbType.Decimal);
                    Paras[20].Value = iSum;
                    Paras[21] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                    Paras[21].Value = CheckBatch(IsEnableBatch, NowRow.Batch);

                    sqlstring = "INSERT INTO PU_ArrivalVouchs (ID,AutoID,ivouchrowno,cInvCode,iQuantity,iPOsID,cUnitID,iCorId,cordercode,carrivalcode,bTaxCost,iTaxRate,SoType,iinvexchrate,iExpiratDateCalcu,iOriCost,iOriTaxCost,iOriMoney,iOriTaxPrice,iOriSum,iCost,iMoney,iTaxPrice,iSum) VALUES ( @ID, @AutoID, @ivouchrowno, @cInvCode, @iQuantity, @iPOsID, @cUnitID, @iCorId, @cordercode, @carrivalcode, @bTaxCost, @iTaxRate, 0, 1, 0, @iOriCost, @iOriTaxCost, @iOriMoney, @iOriTaxPrice, @iOriSum, @iCost, @iMoney, @iTaxPrice, @iSum ) ";
                    DbHelperSQL.Query(sqlstring, WebApiApplication.TimeOut, Paras);

                    Paras = new SqlParameter[2];
                    Paras[0] = new SqlParameter("@iArrQTY", SqlDbType.Decimal);
                    Paras[0].Value = iArrQTY;
                    Paras[1] = new SqlParameter("@iPOsID", SqlDbType.Int);
                    Paras[1].Value = iPOsID;
                    if (cBusType == "普通采购")
                    {
                        DbHelperSQL.Query("update PO_Podetails set iArrQTY=@iArrQTY where ID=@iPOsID", WebApiApplication.TimeOut, Paras);
                    }
                    else if (cBusType == "委外加工")
                    {
                        DbHelperSQL.Query("update OM_MODetails set iArrQTY=@iArrQTY where MODetailsID=@iPOsID", WebApiApplication.TimeOut, Paras);
                    }

                    fRealQuantity += NowRow.Quantity;
                    fValidQuantity += NowRow.Quantity;
                    fRefuseQuantity += (0 - NowRow.Quantity);
                    fSumRefuseQuantity += (0 - NowRow.Quantity);

                    Paras = new SqlParameter[5];
                    Paras[0] = new SqlParameter("@fRealQuantity", SqlDbType.Decimal);
                    Paras[0].Value = fRealQuantity;
                    Paras[1] = new SqlParameter("@fValidQuantity", SqlDbType.Decimal);
                    Paras[1].Value = fValidQuantity;
                    Paras[2] = new SqlParameter("@fRefuseQuantity", SqlDbType.Decimal);
                    Paras[2].Value = fRefuseQuantity;
                    Paras[3] = new SqlParameter("@fSumRefuseQuantity", SqlDbType.Decimal);
                    Paras[3].Value = fSumRefuseQuantity;
                    Paras[4] = new SqlParameter("@iCorId", SqlDbType.Int);
                    Paras[4].Value = BillItemCopy(NowRow.SourceAutoId, DBNull.Value);

                    DbHelperSQL.Query("update PU_ArrivalVouchs set fRealQuantity=@fRealQuantity,fValidQuantity=@fValidQuantity,fRefuseQuantity=@fRefuseQuantity,fSumRefuseQuantity=@fSumRefuseQuantity where Autoid =@iCorId", WebApiApplication.TimeOut, Paras);


                    RowNo++;
                    iChildId--;
                }
                ID = iFatherId;
                Rows = GetVoucherAutoId("PU", ID);
                ts.Complete();
            }
            return true;
        }


        #endregion ///单据Push业务处理

        #region ///辅助方法
        /// <summary>
        /// 构建登录对象
        /// </summary>
        /// <param name="sSubId">U8子模块</param>
        /// <param name="sAccId">账套ID</param>
        /// <param name="sYear">年份</param>
        /// <param name="sUserId">用户账号</param>
        /// <param name="sPassword">用户密码</param>
        /// <param name="sDate">登陆日期</param>
        /// <param name="sServer">登陆服务器地址</param>
        /// <param name="sSerial">默认空</param>
        /// <returns></returns>
        private static U8Login.clsLogin GetU8Login(String sSubId, String sAccId, String sYear, String sUserId, String sPassword, String sDate, String sServer, String sSerial)
        {
            U8Login.clsLogin U8Login = new U8Login.clsLogin();
            bool bSucess = false;            
            bSucess = U8Login.Login(ref sSubId, ref sAccId, ref sYear, ref sUserId, ref sPassword, ref sDate, ref sServer, ref sSerial);
            if (bSucess == false)
            {
                String errMsg = "登陆失败,原因:" + U8Login.ShareString;
                throw new Exception(errMsg);
            }
            else
            {
                return U8Login;
            }           
        }

        /// <summary>
        /// 生成系统日志
        /// </summary>
        /// <param name="InterfaceName">接口名称</param>
        /// <param name="ExtSysRequestId">外部系统请求Id</param>
        /// <param name="JsonString">请求的JSON字符串</param>
        /// <param name="success">执行结果</param>
        /// <param name="cCode">返回的单据号</param>
        /// <param name="message">返回的消息</param>
        private void CreateLog(string InterfaceName, string ExtSysRequestId, string JsonString, bool success, string cCode, string message)
        {
            using (TransactionScope ts2 = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                SqlParameter[] Params = new SqlParameter[6];
                Params[0] = new SqlParameter("@ExtSysRequestId", SqlDbType.NVarChar, 50);
                Params[0].Value = ExtSysRequestId;
                Params[1] = new SqlParameter("@JsonString", SqlDbType.NVarChar, 4000);
                Params[1].Value = JsonString;
                Params[2] = new SqlParameter("@success", SqlDbType.Bit);
                Params[2].Value = success;
                Params[3] = new SqlParameter("@cCode", SqlDbType.NVarChar, 20);
                Params[3].Value = cCode;
                Params[4] = new SqlParameter("@message", SqlDbType.NVarChar, 4000);
                Params[4].Value = message;
                Params[5] = new SqlParameter("@InterfaceName", SqlDbType.NVarChar, 100);
                Params[5].Value = InterfaceName;
                DbHelperSQL.Query("INSERT INTO U8InterFaceLog (InterfaceName, ExtSysRequestId, JsonString, success, cCode, message ) VALUES (@InterfaceName, @ExtSysRequestId, @JsonString, @success, @cCode, @message )", WebApiApplication.TimeOut, Params);
                ts2.Complete();
            }
        }

        /// <summary>
        /// 获取单据ID号
        /// </summary>
        /// <param name="cVouchType">单据类型</param>
        /// <param name="iAmount">子表总行数</param>
        /// <param name="iFatherId">主表ID号</param>
        /// <param name="iChildId">子表ID号</param>
        private void GetID(string cVouchType, int iAmount, out int iFatherId, out int iChildId)
        {
            string cAcc_Id = DbHelperSQL.ExecuteScalar("select dbo.fn_fd_getAccId()").ToString();
            SqlParameter[] Paras = new SqlParameter[5];
            Paras[0] = new SqlParameter("@cAcc_Id", SqlDbType.NVarChar, 3);
            Paras[0].Value = cAcc_Id;
            Paras[1] = new SqlParameter("@cVouchType", SqlDbType.NVarChar, 50);
            Paras[1].Value = cVouchType;
            Paras[2] = new SqlParameter("@iAmount", SqlDbType.Int);
            Paras[2].Value = iAmount;
            Paras[3] = new SqlParameter("@iFatherId", SqlDbType.Int);
            Paras[3].Direction = ParameterDirection.Output;
            Paras[4] = new SqlParameter("@iChildId", SqlDbType.Int);
            Paras[4].Direction = ParameterDirection.Output;
            DbHelperSQL.RunProcedure("sp_GetID", Paras, WebApiApplication.TimeOut);
            iFatherId = Convert.ToInt32(Paras[3].Value);
            iChildId = Convert.ToInt32(Paras[4].Value);
        }

        /// <summary>
        /// 检查单据号是否重复
        /// </summary>
        /// <param name="FieldName">单据号字段名</param>
        /// <param name="cCode">单据号</param>
        /// <param name="TableName">表名</param>
        /// <returns></returns>
        private bool CheckVoucherNo(string FieldName, string cCode, string TableName)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@cCode", SqlDbType.NVarChar, 30);
            Params[0].Value = cCode;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from " + TableName + " where " + FieldName + " =@cCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1)
            {
                return true;
            }
            else
            {
                if (DataSet1.Tables[0].Rows.Count < 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        /// <summary>
        /// 检查主表ID是否重复
        /// </summary>
        /// <param name="ID">ID</param>
        /// <param name="TableName">表名</param>
        /// <returns></returns>
        private bool CheckMainID(int ID, string TableName)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@ID", SqlDbType.Int);
            Params[0].Value = ID;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from " + TableName + " where ID =@ID", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1)
            {
                return true;
            }
            else
            {
                if (DataSet1.Tables[0].Rows.Count < 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 检查部门编码是否存在
        /// </summary>
        /// <param name="cDepCode">部门编码</param>
        /// <returns></returns>
        private bool CheckDepartment(string cDepCode)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@cDepCode", SqlDbType.NVarChar, 12);
            Params[0].Value = cDepCode;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from Department where cDepCode =@cDepCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 检查存货编码是否存在
        /// </summary>
        /// <param name="cInvCode">存货编码</param>
        /// <returns></returns>
        private bool CheckcInvCode(string cInvCode)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
            Params[0].Value = cInvCode;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from Inventory where cInvCode =@cInvCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 检查系统是否启用批次
        /// </summary>
        /// <param name="cInvCode ">存货编码</param>
        /// <returns></returns>
        private bool CheckSystemIsBatch(string cInvCode)
        {
            bool IsBatch = Convert.ToBoolean(GetSystemConfig("ST", "bBatch"));
            if (IsBatch)
            {
                return Convert.ToBoolean(DbHelperSQL.ExecuteScalar("SELECT ISNULL(bInvBatch,0) FROM Inventory  WHERE cInvCode = '" + cInvCode + "'"));
            }
            return IsBatch;
        }
        /// <summary>
        /// 获取U8系统的业务配置
        /// </summary>
        /// <param name="cSysID">系统模块ID</param>
        /// <param name="Id">业务配置cId</param>
        /// <returns></returns>
        private object GetSystemConfig(string cSysID, string cName)
        {
            return DbHelperSQL.ExecuteScalar("SELECT cValue FROM accinformation WHERE cSysID = '" + cSysID + "' and cName='" + cName + "'");
        }
        /// <summary>
        /// 检查子表ID是否重复
        /// </summary>
        /// <param name="AutoID">AutoID</param>
        /// <param name="TableName">表名</param>
        /// <returns></returns>
        private bool CheckSubID(int AutoID, string TableName)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@AutoID", SqlDbType.Int);
            Params[0].Value = AutoID;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from " + TableName + " where AutoID =@AutoID", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1)
            {
                return true;
            }
            else
            {
                if (DataSet1.Tables[0].Rows.Count < 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        /// <summary>
        /// 检查子表ID与存货编码是否一致
        /// </summary>
        /// <param name="AutoID">AutoID</param>
        /// <param name="TableName">表名</param>
        /// <param name="InvCode">存货编码</param>
        /// <returns></returns>
        private bool CheckSubInvCode(int AutoID, string TableName,string InvCode)
        {
            SqlParameter[] Params = new SqlParameter[2];
            Params[0] = new SqlParameter("@AutoID", SqlDbType.Int);
            Params[0].Value = AutoID;
            Params[1] = new SqlParameter("@cInvCode", SqlDbType.NVarChar,50);
            Params[1].Value = InvCode;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from " + TableName + " where AutoID =@AutoID and cInvCode=@cInvCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1)
            {
                return false;
            }
            else
            {
                if (DataSet1.Tables[0].Rows.Count < 1)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

        /// <summary>
        /// 检查指定的表中的某字段中的某值是否存在
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="where">where子句<param>
        /// <returns></returns>
        private bool CheckTableValueExist2(string TableName, string where)
        {
            string SqlString = "";
            if (string.IsNullOrEmpty(where))
            {
                return false;
            }
            else
            {
                SqlString = "select 1 from " + TableName + " where " + where;
            }
            DataSet DataSet1 = DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 检查指定的表中的某字段中的某值是否存在
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="ColumnName">列名</param>
        /// <param name="Value">检查的值</param>
        /// <returns></returns>
        private bool CheckTableValueExist(string TableName, string ColumnName, dynamic Value)
        {
            string SqlString = "";
            if (Value == null)
            {
                Value = "";
            }
            if (Value is string)
            {
                SqlString = "select 1 from " + TableName + " where " + ColumnName + " ='" + Value + "'";
            }
            else
            {
                SqlString = "select 1 from " + TableName + " where " + ColumnName + " =" + Value;
            }
            //File.AppendAllText(@"D:\U8Interface\debug.txt", DateTime.Now.ToString() + SqlString +"\n");//添加至文件
            DataSet DataSet1 = DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        private string CheckDBNULL(object Value)
        {
            if (Value == DBNull.Value)
            {
                return "";
            }
            else
            {
                return Value.ToString();
            }
        }
        private dynamic DataConvert(VariateType Type, object Value)
        {
            if (Value == DBNull.Value)
            {
                if (Type == VariateType.Int32)
                {
                    return 0;
                }
                else if (Type == VariateType.Int64)
                {
                    return 0;
                }
                else if (Type == VariateType.Decimal)
                {
                    return 0;
                }
                else if (Type == VariateType.Boolean)
                {
                    return false;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                if (Type == VariateType.Int32)
                {
                    return Convert.ToInt32(Value);
                }
                else if (Type == VariateType.Int64)
                {
                    return Convert.ToInt64(Value);
                }
                else if (Type == VariateType.Decimal)
                {
                    return Convert.ToDecimal(Value);
                }
                else if (Type == VariateType.Boolean)
                {
                    return Convert.ToBoolean(Value);
                }
                else
                {
                    return Convert.ToString(Value);
                }
            }
        }
        /// <summary>
        /// 参照单据值复制
        /// </summary>
        /// <param name="UpBillValue">参照单据的值</param>
        /// <param name="JsonValue">Json提交的值</param>
        /// <returns></returns>
        private object BillItemCopy(object JsonValue, object UpBillValue)
        {
            if (JsonValue is null)
            {
                return UpBillValue;
            }
            else if (JsonValue is string)
            {
                if (Convert.ToString(JsonValue) == " " || Convert.ToString(JsonValue) == "" || JsonValue == null)
                {
                    return UpBillValue;
                }
                else
                {
                    return Convert.ToString(JsonValue).Trim();
                }

            }
            else if (JsonValue is decimal)
            {
                if (Convert.ToDecimal(JsonValue) == 0)
                {
                    return UpBillValue;
                }
                else
                {
                    return JsonValue;
                }
            }
            else if (JsonValue is Int32 || JsonValue is Int64 || JsonValue is Int16)
            {
                if (Convert.ToInt32(JsonValue) == 0)
                {
                    return UpBillValue;
                }
                else
                {
                    return JsonValue;
                }
            }
            else
            {
                return DBNull.Value;
            }
        }
        /// <summary>
        /// 检查批次
        /// </summary>
        /// <param name="IsEnableBatch">是否启用批次</param>
        /// <param name="cBatch">批次号</param>
        /// <returns></returns>
        private object CheckBatch(bool IsEnableBatch, string cBatch)
        {
            if (IsEnableBatch)
            {
                return cBatch;
            }
            else
            {
                return DBNull.Value;
            }
        }
        /// <summary>
        /// 获取默认单据模板号
        /// </summary>
        /// <param name="CardNumber">单据类型编码</param>
        /// <returns></returns>
        private int GetVoucherTemplateId(string CardNumber)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@CardNumber", SqlDbType.NVarChar, 100);
            Params[0].Value = CardNumber;
            DataSet DataSet1 = DbHelperSQL.Query("SELECT DEF_ID FROM vouchers_base WHERE CardNumber=@CardNumber", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(DataSet1.Tables[0].Rows[0][0]);
            }
        }
        /// <summary>
        /// 返回子表ID
        /// </summary>
        /// <param name="ID">主表Id</param>
        /// <returns></returns>
        private List<ReturnRows> GetVoucherAutoId(string VoucherCode,int ID)
        {
            List<ReturnRows> Rows = new List<ReturnRows>();
            string SQLString = "";
            if (VoucherCode == "PU")
            {
                SQLString = "SELECT ivouchrowno,AutoID FROM PU_ArrivalVouchs WHERE ID=" + ID;
                DataRowCollection DataRows = DbHelperSQL.Query(SQLString).Tables[0].Rows;
                foreach (DataRow row in DataRows)
                {
                    ReturnRows returnRows = new ReturnRows();
                    returnRows.RowNo = Convert.ToInt32(row["ivouchrowno"]);
                    returnRows.AutoId = Convert.ToInt32(row["AutoID"]);
                    Rows.Add(returnRows);
                }
            }
            else if (VoucherCode == "01")
            {
                SQLString = "SELECT irowno,AutoID FROM rdrecords01 WHERE ID=" + ID;
                DataRowCollection DataRows = DbHelperSQL.Query(SQLString).Tables[0].Rows;
                foreach (DataRow row in DataRows)
                {
                    ReturnRows returnRows = new ReturnRows();
                    returnRows.RowNo = Convert.ToInt32(row["irowno"]);
                    returnRows.AutoId = Convert.ToInt32(row["AutoID"]);
                    Rows.Add(returnRows);
                }
            }
            else if (VoucherCode == "08")
            {
                SQLString = "SELECT irowno,AutoID FROM rdrecords08 WHERE ID=" + ID;
                DataRowCollection DataRows = DbHelperSQL.Query(SQLString).Tables[0].Rows;
                foreach (DataRow row in DataRows)
                {
                    ReturnRows returnRows = new ReturnRows();
                    returnRows.RowNo = Convert.ToInt32(row["irowno"]);
                    returnRows.AutoId = Convert.ToInt32(row["AutoID"]);
                    Rows.Add(returnRows);
                }
            }
            else if (VoucherCode == "32")
            {
                SQLString = "SELECT irowno,AutoID FROM rdrecords32 WHERE ID=" + ID;
                DataRowCollection DataRows = DbHelperSQL.Query(SQLString).Tables[0].Rows;
                foreach (DataRow row in DataRows)
                {
                    ReturnRows returnRows = new ReturnRows();
                    returnRows.RowNo = Convert.ToInt32(row["irowno"]);
                    returnRows.AutoId = Convert.ToInt32(row["AutoID"]);
                    Rows.Add(returnRows);
                }
            }
            else if (VoucherCode == "10")
            {
                SQLString = "SELECT irowno,AutoID FROM rdrecords10 WHERE ID=" + ID;
                DataRowCollection DataRows = DbHelperSQL.Query(SQLString).Tables[0].Rows;
                foreach (DataRow row in DataRows)
                {
                    ReturnRows returnRows = new ReturnRows();
                    returnRows.RowNo = Convert.ToInt32(row["irowno"]);
                    returnRows.AutoId = Convert.ToInt32(row["AutoID"]);
                    Rows.Add(returnRows);
                }
            }
            return Rows;
        }
        /// <summary>
        /// 修改现存量
        /// </summary>
        /// <param name="IsEnableBatch">是否启用批次</param>
        /// <param name="cWhCode">仓库编码</param>
        /// <param name="cInvCode">存货编码</param>
        /// <param name="cBatch">批次</param>
        /// <param name="iQuantity">数量</param>
        /// <param name="IsInStorage">是否入库操作</param>
        /// <param name="IsPredict">是否为预计出入库</param>
        /// <param name="IsUpdatePredict">是否更新预计出入库数量</param>
        private void UpdateCurrentStock(bool IsEnableBatch, string cWhCode, string cInvCode, string cBatch, decimal iQuantity, bool IsInStorage, bool IsPredict, bool IsUpdatePredict)
        {
            SqlParameter[] Params = new SqlParameter[3];
            Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
            Params[0].Value = cInvCode;
            Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
            Params[1].Value = cWhCode;
            Params[2] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
            Params[2].Value = cBatch;
            string SqlString = "";
            if (IsEnableBatch)
            {
                SqlString = "select 1 from CurrentStock where cInvCode =@cInvCode and cWhCode =@cWhCode and cBatch=@cBatch";
            }
            else
            {
                SqlString = "select 1 from CurrentStock where cInvCode =@cInvCode and cWhCode =@cWhCode";
            }

            DataSet DataSet1 = DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                int ItemId;
                Params = new SqlParameter[1];
                Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                Params[0].Value = cInvCode;

                DataSet1 = DbHelperSQL.Query("select id from SCM_ITEM where cInvCode =@cInvCode", WebApiApplication.TimeOut, Params);
                if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
                {
                    DbHelperSQL.Query("insert into SCM_ITEM (cInvCode) values (@cInvCode)", WebApiApplication.TimeOut, Params);
                    DataSet1 = DbHelperSQL.Query("select id from SCM_ITEM where cInvCode =@cInvCode", WebApiApplication.TimeOut, Params);
                    ItemId = Convert.ToInt32(DataSet1.Tables[0].Rows[0]["id"]);
                }
                else
                {
                    ItemId = Convert.ToInt32(DataSet1.Tables[0].Rows[0]["id"]);
                }
                Params = new SqlParameter[5];
                Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                Params[0].Value = cInvCode;
                Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                Params[1].Value = cWhCode;
                Params[2] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                Params[2].Value = iQuantity;
                Params[3] = new SqlParameter("@ItemId", SqlDbType.Int);
                Params[3].Value = ItemId;
                Params[4] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                Params[4].Value = cBatch;
                if (IsInStorage) //入库
                {
                    if (IsPredict)   //预计出入库
                    {
                        if (IsEnableBatch)
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,cBatch,ItemId,fInQuantity,isodid) VALUES (@cWhCode,@cInvCode,@cBatch,@ItemId,@iQuantity,'') ";
                        }
                        else
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,ItemId,fInQuantity,isodid) VALUES (@cWhCode,@cInvCode,@ItemId,@iQuantity,'') ";
                        }
                    }
                    else   //正常出入库
                    {
                        if (IsEnableBatch)
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,cBatch,ItemId,iQuantity,isodid) VALUES (@cWhCode,@cInvCode,@cBatch,@ItemId,@iQuantity,'')";
                        }
                        else
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,ItemId,iQuantity,isodid) VALUES (@cWhCode,@cInvCode,@ItemId,@iQuantity,'')";
                        }
                    }
                }
                else
                {
                    if (IsPredict)   //预计出入库
                    {
                        if (IsEnableBatch)
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,cBatch,ItemId,fOutQuantity,isodid) VALUES (@cWhCode,@cInvCode,@cBatch,@ItemId,@iQuantity,'')";
                        }
                        else
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,ItemId,fOutQuantity,isodid) VALUES (@cWhCode,@cInvCode,@ItemId,@iQuantity,'')";
                        }
                    }
                    else   //正常出入库
                    {
                        if (IsEnableBatch)
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,cBatch,ItemId,iQuantity,isodid) VALUES (@cWhCode,@cInvCode,@cBatch,@ItemId,(0-@iQuantity),'')";
                        }
                        else
                        {
                            SqlString = "INSERT INTO CurrentStock (cWhCode,cInvCode,ItemId,iQuantity,isodid) VALUES (@cWhCode,@cInvCode,@ItemId,(0-@iQuantity),'')";
                        }
                    }
                }
                DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut, Params);


            }
            else
            {
                if (IsInStorage) //入库
                {

                    if (IsPredict)   //预计出入库
                    {
                        Params = new SqlParameter[4];
                        Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                        Params[0].Value = cInvCode;
                        Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Params[1].Value = cWhCode;
                        Params[2] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                        Params[2].Value = iQuantity;
                        Params[3] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                        Params[3].Value = cBatch;
                        if (IsEnableBatch)
                        {
                            SqlString = "UPDATE CurrentStock set fInQuantity =isnull(fInQuantity,0)+@iQuantity where cInvCode =@cInvCode and cWhCode =@cWhCode AND cBatch=@cBatch";
                        }
                        else
                        {
                            SqlString = "UPDATE CurrentStock set fInQuantity =isnull(fInQuantity,0)+@iQuantity where cInvCode =@cInvCode and cWhCode =@cWhCode";
                        }

                    }
                    else   //正常出入库
                    {
                        Params = new SqlParameter[5];
                        Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                        Params[0].Value = cInvCode;
                        Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Params[1].Value = cWhCode;
                        Params[2] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                        Params[2].Value = iQuantity;
                        Params[3] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                        Params[3].Value = cBatch;
                        Params[4] = new SqlParameter("@IsUpdatePredict", SqlDbType.Bit);
                        Params[4].Value = IsUpdatePredict;
                        if (IsEnableBatch)
                        {
                            SqlString = "UPDATE CurrentStock SET iQuantity = ISNULL(iQuantity, 0) + @iQuantity, fInQuantity = (CASE @IsUpdatePredict WHEN 0 THEN fInQuantity WHEN 1 THEN (ISNULL(fInQuantity, 0) - @iQuantity) END ) WHERE cInvCode = @cInvCode AND cWhCode = @cWhCode AND cBatch=@cBatch";
                        }
                        else
                        {
                            SqlString = "UPDATE CurrentStock SET iQuantity = ISNULL(iQuantity, 0) + @iQuantity, fInQuantity = (CASE @IsUpdatePredict WHEN 0 THEN fInQuantity WHEN 1 THEN (ISNULL(fInQuantity, 0) - @iQuantity) END ) WHERE cInvCode = @cInvCode AND cWhCode = @cWhCode";
                        }
                    }
                }
                else
                {
                    if (IsPredict)   //预计出入库
                    {
                        Params = new SqlParameter[4];
                        Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                        Params[0].Value = cInvCode;
                        Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Params[1].Value = cWhCode;
                        Params[2] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                        Params[2].Value = iQuantity;
                        Params[3] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                        Params[3].Value = cBatch;
                        if (IsEnableBatch)
                        {
                            SqlString = "UPDATE CurrentStock set fOutQuantity =isnull(fOutQuantity,0)+@iQuantity where cInvCode =@cInvCode and cWhCode =@cWhCode and cBatch=@cBatch";
                        }
                        else
                        {
                            SqlString = "UPDATE CurrentStock set fOutQuantity =isnull(fOutQuantity,0)+@iQuantity where cInvCode =@cInvCode and cWhCode =@cWhCode";
                        }
                    }
                    else   //正常出入库
                    {
                        Params = new SqlParameter[5];
                        Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
                        Params[0].Value = cInvCode;
                        Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
                        Params[1].Value = cWhCode;
                        Params[2] = new SqlParameter("@iQuantity", SqlDbType.Decimal);
                        Params[2].Value = iQuantity;
                        Params[3] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 60);
                        Params[3].Value = cBatch;
                        Params[4] = new SqlParameter("@IsUpdatePredict", SqlDbType.Bit);
                        Params[4].Value = IsUpdatePredict;
                        if (IsEnableBatch)
                        {
                            //SqlString = "UPDATE CurrentStock set iQuantity=isnull(iQuantity,0)-@iQuantity, fOutQuantity=(Case @IsUpdatePredict when 0 then fOutQuantity when 1 then (isnull(fOutQuantity,0)-@iQuantity) end) where cInvCode =@cInvCode and cWhCode =@cWhCode and cBatch=@cBatch";

                            //SqlString = @"DECLARE @iQuantity INT
                            //            DECLARE @fOutQuantity INT
                            //            SET @fOutQuantity=@iQuantity
                            //            DECLARE @AutoID INT,@iQty UDT_LogisticQuantity,@fOutQty UDT_LogisticQuantity
                            //            DECLARE cur1 CURSOR FOR 
                            //             SELECT AutoID,ISNULL(iQuantity,0),ISNULL(fOutQuantity,0) FROM CurrentStock WHERE cInvCode =@cInvCode and cWhCode =@cWhCode and ISNULL(iQuantity,0)=0 AND (ISNULL(cBatch,'')='' OR cBatch=@cBatch) ORDER BY ISNULL(iQuantity,0)
                            //            OPEN cur1
                            //            FETCH NEXT FROM cur1 INTO @AutoID,@iQty,@fOutQty
                            //            WHILE @@FETCH_STATUS = 0
                            //            BEGIN	
                            //                UPDATE CurrentStock set 
                            //              iQuantity=CASE WHEN (@iQty-@iQuantity)<0 THEN 0 ELSE (@iQty-@iQuantity) END ,
                            //              fOutQuantity=Case @IsUpdatePredict when 0 THEN fOutQuantity ELSE CASE WHEN (@fOutQty-@fOutQuantity)<0 THEN 0 ELSE (@fOutQty-@fOutQuantity) END END		
                            //             WHERE AutoId=@AutoID
                            //             SET @iQuantity=ABS(@iQty-@iQuantity)
                            //             SET @fOutQuantity=ABS(@fOutQty-@fOutQuantity)
                            //                FETCH NEXT FROM cur1 INTO @AutoID,@iQty,@fOutQty
                            //            END
                            //            CLOSE cur1
                            //            DEALLOCATE cur1";
                            SqlString = "UPDATE CurrentStock set iQuantity=isnull(iQuantity,0)-@iQuantity, fOutQuantity=(Case @IsUpdatePredict when 0 then fOutQuantity when 1 then (isnull(fOutQuantity,0)-@iQuantity) end) where cInvCode =@cInvCode and cWhCode =@cWhCode and cBatch=@cBatch";
                        }
                        else
                        {
                            SqlString = "UPDATE CurrentStock set iQuantity=isnull(iQuantity,0)-@iQuantity, fOutQuantity=(Case @IsUpdatePredict when 0 then fOutQuantity when 1 then (isnull(fOutQuantity,0)-@iQuantity) end) where cInvCode =@cInvCode and cWhCode =@cWhCode";
                        }
                    }
                }
                DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut, Params);
            }
        }
        /// <summary>
        /// 获取现存量
        /// </summary>
        /// <param name="cInvCode">存货编码</param>
        /// <param name="cWhCode">仓库编码</param>
        /// <param name="cBatch">批次号</param>
        /// <returns></returns>
        private decimal GetCurrentStock(string cInvCode, string cWhCode, string cBatch)
        {
            bool IsEnableBatch = Convert.ToBoolean(GetSystemConfig("ST", "bBatch"));
            SqlParameter[] Params = new SqlParameter[3];
            Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
            Params[0].Value = cInvCode;
            Params[1] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
            Params[1].Value = cWhCode;
            Params[2] = new SqlParameter("@cBatch", SqlDbType.NVarChar, 80);
            Params[2].Value = cBatch;

            string SqlString;
            if (IsEnableBatch)
            {
                SqlString = "select iQuantity from CurrentStock where cInvCode =@cInvCode and cWhCode =@cWhCode and cBatch=@cBatch";
            }
            else
            {
                SqlString = "select iQuantity from CurrentStock where cInvCode =@cInvCode and cWhCode =@cWhCode";
            }

            DataSet DataSet1 = DbHelperSQL.Query(SqlString, WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return 0;
            }
            else
            {
                return Convert.ToDecimal(DataSet1.Tables[0].Rows[0]["iQuantity"]);
            }
        }
        /// <summary>
        /// 检查产品入库数量是否符合材料出库比例
        /// </summary>
        /// <param name="irowno">入库单行号</param>
        /// <param name="iMPoIds">参照的生产订单子表ID</param>
        /// <param name="iQuantity">数量,数量为负数时代表红字单据</param>
        /// <param name="Msg">返回错误消息</param>
        /// <returns></returns>
        private bool CheckMOPickingTheProportion(int irowno, Int64 iMPoIds, decimal iQuantity, out string Msg)
        {
            Msg = "";
            decimal YRKQty;
            decimal MOQty;
            MOQty = Convert.ToDecimal(DbHelperSQL.ExecuteScalar("SELECT Qty FROM mom_orderdetail WHERE MoDId = " + iMPoIds));
            YRKQty = Convert.ToDecimal(DbHelperSQL.ExecuteScalar("SELECT isnull(QualifiedInQty,0) as QualifiedInQty FROM mom_orderdetail WHERE MoDId = " + iMPoIds));
            DataTable DataTable1 = DbHelperSQL.Query("SELECT ISNULL(IssQty, 0) AS IssQty, InvCode, SortSeq, Qty FROM mom_moallocate WHERE MoDId = " + iMPoIds, WebApiApplication.TimeOut).Tables[0];
            foreach (DataRow dr in DataTable1.Rows)
            {
                decimal IssQty = DataConvert(VariateType.Decimal, dr["IssQty"]);
                string InvCode = CheckDBNULL(dr["InvCode"]);
                int SortSeq = Convert.ToInt32(dr["SortSeq"]);
                decimal Qty = DataConvert(VariateType.Decimal, dr["Qty"]);
                decimal DWQty = Qty / MOQty;
                decimal TheQty;
                decimal TheIssQty;
                if (Qty != 0)
                {
                    TheQty = iQuantity * DWQty;
                    TheIssQty = YRKQty * DWQty;
                    if (DWQty * (iQuantity + YRKQty) > IssQty)
                    {
                        Msg = "入库单第[" + irowno + "]行,生产订单子件第[" + SortSeq + "]行,存货[" + InvCode + "]材料领料数量不足.单位用量[" + DWQty + "]本次入库数量[" + iQuantity + "]已入库数量[" + YRKQty + "]本次入库理论应领数量[" + DWQty * (iQuantity + YRKQty) + "]已领料数量[" + IssQty + "]";
                        return false;
                    }
                }
            }
            return true;

        }
        /// <summary>
        /// 返回单据单号
        /// </summary>
        /// <param name="TableName">表名</param>
        /// <param name="FieldId">Id字段名</param>
        /// <param name="FieldVoucherName">单据编号字段名</param>
        /// <param name="Id">单据Id</param>
        /// <returns></returns>
        private string GetVoucherName(string TableName,string FieldId,string FieldVoucherName,int Id)
        {
            string sqlstring = string.Format("select {0} from {1} where {2}={3}", FieldVoucherName, TableName, FieldId, Id);
            return DbHelperSQL.ExecuteScalar(sqlstring).ToString();
        }
        /// <summary>
        /// 获取单位编码
        /// </summary>
        /// <param name="cInvCode">存货编码</param>
        /// <returns></returns>
        private string GetAssUnit(string cInvCode)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@cInvCode", SqlDbType.NVarChar, 60);
            Params[0].Value = cInvCode;
            DataSet DataSet1 = DbHelperSQL.Query("select cComUnitCode from Inventory where cInvCode =@cInvCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return "";
            }
            else
            {
                return CheckDBNULL(DataSet1.Tables[0].Rows[0]["cComUnitCode"]);
            }
        }
        /// <summary>
        /// 检查仓库编码是否存在
        /// </summary>
        /// <param name="cWhCode">仓库编码</param>
        /// <returns></returns>
        private bool CheckWarehouse(string cWhCode)
        {
            SqlParameter[] Params = new SqlParameter[1];
            Params[0] = new SqlParameter("@cWhCode", SqlDbType.NVarChar, 10);
            Params[0].Value = cWhCode;
            DataSet DataSet1 = DbHelperSQL.Query("select 1 from Warehouse where cWhCode =@cWhCode", WebApiApplication.TimeOut, Params);
            if (DataSet1.Tables.Count < 1 || DataSet1.Tables[0].Rows.Count < 1)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 设置MES操作员
        /// </summary>
        /// <param name="VouchCode">单据代码</param>
        /// <param name="Id">单据Id</param>
        private void SetMESUser(USERPCO.VoucherCO VCO, ADODB.Connection con,ref MSXML2.IXMLDOMDocument2 HeadDom,ref MSXML2.IXMLDOMDocument2 BodyDom,ref MSXML2.IXMLDOMDocument2 PosDom, string VouchCode,int Id,string MESUserName)
        {
            //修改MES操作员
            HeadDom = new MSXML2.DOMDocumentClass();
            BodyDom = new MSXML2.DOMDocumentClass();
            PosDom = new MSXML2.DOMDocumentClass();
            string sErrMsg = "";

            bool IsRun = VCO.Load(VouchCode, "id='" + Id + "'", ref HeadDom, ref BodyDom, ref PosDom, ref sErrMsg);
            if (IsRun == false)
            {
                throw new Exception(sErrMsg);
            }
            MSXML2.IXMLDOMNode HeadNode = HeadDom.selectSingleNode(@"/xml/rs:data/z:row");
            MSXML2.IXMLDOMNode MESUser = HeadNode.attributes.getNamedItem("cDefine11");
            if (MESUser == null)
            {
                MESUser = HeadDom.createAttribute("cDefine11");
                HeadNode.attributes.setNamedItem(MESUser);
            }
            MESUser.nodeValue = MESUserName; //MES操作员

            bool bCheck = true, bBeforCheckStock = true;
            MSXML2.IXMLDOMDocument2 domMsg = new MSXML2.DOMDocumentClass();
            IsRun = VCO.Update(VouchCode, HeadDom, BodyDom, PosDom, ref sErrMsg, ref con, ref domMsg, ref bCheck, ref bBeforCheckStock);
            if (IsRun == false)
            {
                throw new Exception(sErrMsg);
            }
        }
        /// <summary>
        /// 审核单据
        /// </summary>
        /// <param name="VCO"></param>
        /// <param name="con"></param>
        /// <param name="VouchCode"></param>
        /// <param name="Id"></param>
        private void AuditVoucher(USERPCO.VoucherCO VCO, ADODB.Connection con, string VouchCode, int Id)
        {
            bool bCheck = true, bBeforCheckStock = true, bList = false;
            MSXML2.IXMLDOMDocument2 domMsg = new MSXML2.DOMDocumentClass();
            object TimeStamp = null;
            string sErrMsg = "";
            bool IsRun = VCO.Verify(VouchCode, Id, ref sErrMsg, ref con, ref TimeStamp, ref domMsg, ref bCheck, ref bBeforCheckStock, ref bList);
            string errxml = domMsg.xml;
            if (IsRun == false)
            {
                throw new Exception(sErrMsg);
            }            

        }

        private bool GetSQ()
        {

            DateTime _date1 = Convert.ToDateTime(DbHelperSQL.ExecuteScalar("select getdate()"));
            DateTime _date2 = Convert.ToDateTime(MAX_Date);
            if (DateTime.Compare(_date1, _date2) >0)
            {
                return false;
            }
            return true;
        }

        #endregion///辅助方法
    }
}
